Reputation: 85
I'm a little bit confused about the self referencing association in rails.. maybe someone can help me out! I've got a ressource model and I want to add accessories to it. The accessory should be a ressource, too.
So I got this in my ressource.rb:
has_many :accessories, class_name: "Ressource", foreign_key: "accessory_ids"
The problem is that it's not as I would expect it to work. When I call first_ressource.accessories I've got a list of IDs which is perfectly fine. But when I add the same accessory to another ressource (let's say to the second_ressource), the accessory for first_ressource is gone.
I want to be able to store a Ressource with ID=1 in multiple ressources:
first_ressource.accessories = [1,3,5]
second_ressource.accessories = [1,4,6]
Thanks for helping me!
Upvotes: 0
Views: 29
Reputation: 36
You need many to many relationships. In this case, you need a middle model/table to connect multiple accessories to multiple resources.
You can check for details here:
https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
Upvotes: 2