0
0
Ruby on Railsframework~10 mins

Many-to-many with has_many through in Ruby on Rails - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a many-to-many association using has_many through in a Rails model.

Ruby on Rails
class Author < ApplicationRecord
  has_many :author_books
  has_many :books, [1]: :author_books
end
Drag options to blanks, or click blank then click option'
Athrough
Bclass_name
Cdependent
Dsource
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'source' instead of 'through' causes Rails to look for a different association.
Forgetting the 'through' option breaks the many-to-many link.
2fill in blank
medium

Complete the join model declaration to set up the many-to-many relationship.

Ruby on Rails
class AuthorBook < ApplicationRecord
  belongs_to :author
  belongs_to [1]
end
Drag options to blanks, or click blank then click option'
Abook
Bbooks
Cauthor
Dauthors
Attempts:
3 left
💡 Hint
Common Mistakes
Using plural form like 'books' causes errors.
Using the wrong model name breaks the association.
3fill in blank
hard

Fix the error in the Book model to correctly set up the many-to-many association.

Ruby on Rails
class Book < ApplicationRecord
  has_many :author_books
  has_many :authors, [1]: :author_books
end
Drag options to blanks, or click blank then click option'
Asource
Bthrough
Cdependent
Dclass_name
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'source' instead of 'through' causes Rails to fail to find the join model.
Omitting the option breaks the association.
4fill in blank
hard

Fill both blanks to complete the migration for the join table.

Ruby on Rails
class CreateAuthorBooks < ActiveRecord::Migration[6.1]
  def change
    create_table :author_books do |t|
      t.references :[1], null: false, foreign_key: true
      t.references :[2], null: false, foreign_key: true
      t.timestamps
    end
  end
end
Drag options to blanks, or click blank then click option'
Aauthor
Bauthors
Cbook
Dbooks
Attempts:
3 left
💡 Hint
Common Mistakes
Using plural names like 'authors' or 'books' in references causes migration errors.
Forgetting foreign_key: true disables database-level integrity.
5fill in blank
hard

Fill all three blanks to complete the Author model with dependent destroy and source options.

Ruby on Rails
class Author < ApplicationRecord
  has_many :author_books, [1]: :destroy
  has_many :books, [2]: :author_books, [3]: :book
end
Drag options to blanks, or click blank then click option'
Adependent
Bthrough
Csource
Dclass_name
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting dependent causes orphan join records.
Mixing up source and through options.
Using class_name instead of source causes errors.