Right now I have a has_and_belongs_to_many relationship between an
events table and a users table. So the join table rows look something
like this:
event_id user_id
1 2
1 3
1 5
Where those users are added through a list of checkboxes.
The problem is that if I want to edit info. and add for example one more
user, rails will erase all existing data on the join table and replace
it with the new user.
# GET /events/1/edit
def edit
@event = Event.find(params[:id])
@event_categories = EventCategory.find(:all)
@friends = current_user.mutual_friends
end
def update
@event = Event.find(params[:id])
respond_to do |format|
if @event.update_attributes(params[:event])
flash[:notice] = 'Event was successfully updated.'
format.html { redirect_to neighborhood_events_path }
format.xml { head :ok }
else
# Added to show again all the event_categories on the form
@event_categories = EventCategory.find(:all)
format.html { render :action => "edit" }
format.xml { render :xml => @event.errors, :status =>
:unprocessable_entity }
end
end
end
So what's happening is that if I edit an event and choose others friends
(check various checkboxes on the view). This new friends will replace
the old friends in the join table events_users (friends are user
objects). I want this new friends to be added to the join table without
deleting the ones before.
Just took a rough look at your code, and I believe the event[user_ids]
form elements are not used properly. I suggest you take a look at
#17 HABTM Checkboxes - RailsCasts for how it should be done.