Reputation: 9336
I have a question regarding a many-to-many relation ship I would like to represent in my Rails application.
Scenario:
A
and B
A
can have many references to B
B
can be assigned by many A
sAB
-> lets call it C
C
are uniqueActiveRecord
model C
ensures I have validation in place to check the uniqueness of C.a_id
and C.b_id
B
s on the ActiveRecord
A
via A has_many :bs through: :c
(has_many :cs
is done)has_many
give me an attribute_accessor
where I am allowed to set the b
s on A
, or append a new b
on A
What is the best way in rails
to have a many-to-many relation with unique jointable entries?
Upvotes: 0
Views: 30
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