DenicioCode
DenicioCode

Reputation: 9336

Many to many relation for unique join table entries

I have a question regarding a many-to-many relation ship I would like to represent in my Rails application.

Scenario:

What is the best way in rails to have a many-to-many relation with unique jointable entries?

Upvotes: 0

Views: 30

Answers (1)

rewritten
rewritten

Reputation: 16435

That is expected to be the default behavior. Without a better look to your code it's nearly impossible to point out the issue, but it sounds like the associations are not set up correctly.

This is how you do all this while having the guarantees you need:

class Bar < ApplicationRecord
  has_many :bar_foos, inverse_of: :bar
  has_many :foos, through: :bar_foos, source: :foo, inverse_of: :bars
end

class Foo < ApplicationRecord
  has_many :bar_foos, inverse_of: :foo
  has_many :bars, through: :bar_foos, source: :bar, inverse_of: :foos
end

class BarFoo < ApplicationRecord
  belongs_to :bar, inverse_of: :bar_foos
  belongs_to :foo, inverse_of: :bar_foos
end

When adding all the explicit inverses, the framework should fill in the intermediate models for you correctly. Without the inverses, the intermediate models will not get the right attributes, and they will generate the duplication.

Upvotes: 1

Related Questions