Reputation: 3000
I am creating a rails api. I have 2 objects which have a many to many relationship. My api needs to be able to add, modify and remove ids. For example when I call the update
method on objectb
controller. It should accept the new list of objecta
ids and persist. What is the right way to do this?
class objectb < ActiveRecord::Base
has_and_belongs_to_many :objecta
end
class objecta < ActiveRecord::Base
has_and_belongs_to_many :objectb
end
I was thinking of just accepting an array of ids then creating a relationship by doing objecta.objectb.create(ObjectB.find(:object_id))
What is the standard way have managing a many to many relationship in the update
controller?
Upvotes: 0
Views: 88
Reputation: 23661
You can achieve it this way
If you want to override
objecta.objectbs = [ObjectB.find(:objectb_id)]
If you want to add objectb in objecta
objecta.objectbs << ObjectB.find(:objectb_id)
Upvotes: 3