rubenr
rubenr

Reputation: 53

Rails: Relate two records after creation

I have his model in Rails:

class Commission < ActiveRecord::Base
  has_and_belongs_to_many :books
end

class Book < ActiveRecord::Base
  has_and_belongs_to_many :commissions
end

This model generates three tables: commission, book and books_commissions. In the first process of my app generate and save commissions and books without relating entries.

Question: How create a record in books_commissions if I know the book_id and commission_id?

Upvotes: 1

Views: 37

Answers (1)

Chambeur
Chambeur

Reputation: 1619

Lets say you have an object book from the model Book and an object commission from the model Commission.

Then book.commissions << commission should do the trick.

Upvotes: 1

Related Questions