Complete the code to declare a many-to-many association using has_many through in a Rails model.
class Author < ApplicationRecord has_many :author_books has_many :books, [1]: :author_books end
The has_many association uses the through option to specify the join model for many-to-many relationships.
Complete the join model declaration to set up the many-to-many relationship.
class AuthorBook < ApplicationRecord belongs_to :author belongs_to [1] end
The join model belongs to both associated models. Here, it belongs to book (singular).
Fix the error in the Book model to correctly set up the many-to-many association.
class Book < ApplicationRecord has_many :author_books has_many :authors, [1]: :author_books end
The has_many association must use through to specify the join model for many-to-many relations.
Fill both blanks to complete the migration for the join table.
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
The join table references the singular model names author and book to create foreign keys.
Fill all three blanks to complete the Author model with dependent destroy and source options.
class Author < ApplicationRecord has_many :author_books, [1]: :destroy has_many :books, [2]: :author_books, [3]: :book end
dependent: :destroy ensures join records are deleted when an author is deleted. through: :author_books sets the join model. source: :book tells Rails which association to use on the join model.