Has_and_belongs_to_many problems when editing

Hello,

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.

event_id user_id
1 7

Is there a way around this?

Please help! and thanks!

Could you show us the code that led to this?

On Jul 10, 6:49 pm, Elias O. [email protected]

Eric LIn wrote:

Could you show us the code that led to this?

On Jul 10, 6:49�pm, Elias O. [email protected]

Hi,
This is my view code for the edit action.

Editing event

<% form_for ([current_user.neighborhood, @event]) do |f| %>
<%= f.error_messages %>

<%= f.label :date %>
<%= f.datetime_select :date %>

<%= f.label :title %>
<%= f.text_field :title %>

<%= f.label :place %>
<%= f.text_field :place %>

<%= f.label :description %>
<%= f.text_area :description %>

<% # f.label :user_id %>
<% # f.text_field :user_id %> <% # hidden_field(:event, :user_id, { :value => current_user.id } ) %>

<%= f.label :event_category_id %>
<% # f.text_field :event_category_id %> <%= collection_select(:event, :event_category_id, @event_categories, :id, :name) %>

<% unless @friends.empty? %>

    <% for friend in @friends do %>
  • <%= " "+friend.name %>
  • <% end %>
<% end %>

<%= f.submit "Update" %>

<% end %>

<%= link_to ‘Show’,
neighborhood_event_path(current_user.neighborhood,@event) %> |
<%= link_to ‘Back’, neighborhood_events_path(current_user.neighborhood)
%>

The edit and update actions:

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.

Thanks again.

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.

Eric

On Jul 10, 8:07Â pm, Elias O. [email protected]