Elliot
Elliot

Reputation: 13835

referencing parent model in many to many association and join table - Rails 3

So I have books, and authors models.

Books has_many authors, and Authors has_many books

In my routes, books are nested under authors, and I have a join table which connects the two (authors_books).

So a books path would live here: authors/1/books

My question is, in my model if I have a function which is doing XYZ to find/create new books with a find_or_create_by method - how do I make sure it links up the new/found book id with the parent author id in a new record in my authors_books join table?

Upvotes: 0

Views: 183

Answers (1)

Ryan Bigg
Ryan Bigg

Reputation: 107718

You could do this by creating a model in the middle of this association, rather than using a has_and_belongs_to_many. For lack of a better name, I would call this model Authorship and it would look like this:

class Authorship < ActiveRecord::Base
  belongs_to :author
  belongs_to :book
end

Then you would define associations in your Author model to books like this:

class Author < ActiveRecord::Base
  has_many :authorships
  has_many :books, :through => :authorships
end

And the reverse, in your Book model:

class Book < ActiveRecord::Base
  has_many :authorships
  has_many :authors, :through => :authorships
end

This way, you'd still have the "has and belongs to many" functionality that you want, except you would now be able to access records in the join table through the newly created model.

Upvotes: 1

Related Questions