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?
https://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many
Rails guides got all the answers!