Reputation: 11
I have an Opportunity model that belongs_to Section model. Section has_many opportunities.
class Opportunity < ActiveRecord::Base
belongs_to :section
class Section < ActiveRecord::Base
has_many :opportunities
Opportunity model has to have section_id but i would like to be able to also have many sections as involved sections in some cases.
how would it be possible to create? thanks
Upvotes: 0
Views: 55
Reputation: 17834
You need a many-to-many association between, Opportunity
and Section
, for that you need to create a connecting table between the two, create a migration
create_table :opportunities_sections, id: false do |t|
t.belongs_to :opportunity
t.belongs_to :section
end
Then in Opportunity
model, add this line
has_and_belongs_to_many :sections
In Section
model, add this line
has_and_belongs_to_many :opportunities
Finally, remove section_id
column from opportunities
table.
More info on has_and_belongs_to_many
association here
https://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association
You can also achieve many-to-many
association via has_many through
association, the basic difference between has_and_belongs_to_many
and has_many through
is you can create a model class for the connecting table, that way you get more flexibility in terms of saving any additional data with the connection. More info here
https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
What to choose?
Rails guides got all the answers!
Upvotes: 1