Reputation: 4421
I would like to know how to add / remove associations in a form. Lets say I have two models linked by foreign keys
class Event < ActiveRecord::Base
has_and_belongs_to_many :participants
end
class Participant < ActiveRecord::Base
has_and_belongs_to_many :events
end
I have created some forms to edit each model. However, is there a way to use the form to remove/add a participant from/to a lecture? (I guess this would require some javascript to add / remove entries in the view as well as well...)
Upvotes: 1
Views: 200
Reputation: 711
What you are looking for is accepts_nested_attributes_for
and some js magic. Ryan Bates describes this perfectly in some of his free episodes:
And here is the full source code of this episodes.
Maybe you'll have to adapt some things because it's a little old, for instance replace link_to_function
for a simple link_to
with an :onclick
event, but I think pretty much everything else works on Rails 4.
Hope it helps!
Upvotes: 1