user3399101
user3399101

Reputation: 1537

how to add to a many_to_many association

How to add new readers to a magazine subscription?

Basically, I am using a many_to_many association - I have a readers model, a magazines model, and a magazines_readers join table.

create_table :magazines do |t|
t.string :title
t.datetime :created_at
t.datetime :updated_at
end
create_table :readers do |t|
t.string :name
t.datetime :created_at
t.datetime :updated_at
end
create_table :magazines_readers, :id => false do |t|
t.integer :magazine_id
t.integer :reader_id
end

Now, if I do something like:

magazine = Magazine.create(:title => "The Ruby Language Journal")
matz = Reader.find_by_name("Matz")
magazine.readers << matz
matz.magazines.size # => 1

I can add Matz to the magazine subscription, but how do I add matz to the subscription in rails in the view+controller?

In otherwords, in the console I can just append matz - but how is this done in the application? What would the code look like? Would it be in the create action etc...

Please help clear this up for me, thanks!

Upvotes: 1

Views: 66

Answers (3)

shrikant1712
shrikant1712

Reputation: 4446

your models should look like this

magazine.rb

class Magazine < ActiveRecord::Base
   has_many :magazine_readers
   has_many :readers, through: :magazine_reader
end

reader.rb

class Reader < ActiveRecord::Base
   has_many :magazine_readers
   has_many :magazines, through: :magazine_reader
end

magazine_reader.rb file which is your join table. In this you can add other attributes also

class MagazineReader < ActiveRecord::Base
   belongs_to :magazine
   belongs_to :reader
end

For further information you can refer this link

Upvotes: 2

KKB
KKB

Reputation: 558

Model

class Magazine < ActiveRecord::Base

   has_many :magazine_readers
   has_many :readers, through: :magazine_reader

end

class MagazineReader < ActiveRecord::Base

 belongs_to :magazine
 belongs_to :reader

end

class Reader < ActiveRecord::Base

 has_many :magazine_readers
 has_many :magazines, through: :magazine_reader

end

Upvotes: 3

Ali Ismayilov
Ali Ismayilov

Reputation: 5837

You just need to do:

class Magazine < ActiveRecord::Base
  has_and_belongs_to_many :readers
end

class Reader < ActiveRecord::Base
  has_and_belongs_to_many :magazines
end

More here: http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

Upvotes: 1

Related Questions