1

My application has a form to update an Event.

I'd like to be able to add an existing user to this event with a nested form. I use the Ryan Bates "nested_form" gem.

It works great to delete an existing user but how can I add an existing one just with his username?

Model :

class Event < ActiveRecord::Base
 has_many users
 attr_accessible :users_attributes
 accepts_nested_attributes_for :users, :allow_destroy => true
end

Controller :

def update
  if @event.update_attributes(params[:event])
   redirect_to @event
  else
   render :edit
  end
end

View :

= f.fields_for :users do |users_form|
  = users_form.text_field :username
  = users_form.link_to_remove "Remove user"
= f.link_to_add "Add a user", :users
= f.submit

Thanks in advance !

invaino
  • 267
  • 1
  • 4
  • 13

1 Answers1

1

If you want many users coupled to many events, you will need has_many :through relationship. In that case, a relation builds a new row in the database, and in that case it is easier to use the cocoon-gem to dynamically link and unlink pages.

I answered a very similar question, also coupling events and users, here.

If you have any more questions, let me know.

Community
  • 1
  • 1
nathanvda
  • 49,707
  • 13
  • 117
  • 139