Problem with checkboxes updating table

I’m having issues getting checkboxes to update a cross-reference table
correctly. I keep seeing entries in the locations_users table, for
location_id and user_id, “11” and “2”, respectively. The user id is
fine, but there is no such location with id 11. There are only 5
locations and their ids go from 1-5! I can’t seem to find where the 11
is coming from.

This is in the view:
<% Location.find(:all).each do |location| %>
<input type=“checkbox”
name=“user[locations_ids][]”
value="<%= location.id %>"
<% if @user.locations.include?(location) %> checked=“checked”
<% end %> />
<%= location.name %>
<% end %>
This is in the controller:

[code=]def edit
@user = User.find(params[:id])
@locations = Location.find(:all)
@locationsusers = LocationsUser.new
end

def update
@user = User.find(params[:id])
@locations = Location.find(:all)
@locations.each do |location|
@locationsids = location.id
end
@locationsusers = LocationsUser.new(params[:locations_users])
@locationsusers.user_id = @user.id
@locationsusers.location_id = @locationsids.id
if @locationsusers.update_attributes(params[:locations_users])
flash[:notice] = ‘User was successfully updated.’
redirect_to :action => ‘list’
else
render :action => ‘edit’
end
end
Have a look at the relevant parts of the output and notice how the
line…

“SELECT * FROM locations INNER JOIN locations_users ON locations.id =
locations_users.location_id WHERE (locations_users.user_id = 2 )”

is not repeated in the ‘update’ action:

Processing UserController#edit
Parameters: {“action”=>“edit”, “id”=>“2”, “controller”=>“user”}
User Columns (0.001195) SHOW FIELDS FROM users
User Load (0.000083) SELECT * FROM users WHERE (users.id = 2)
LocationsUser Columns (0.000656) SHOW FIELDS FROM locations_users
Location Load (0.000129) SELECT * FROM locations
Rendering within layouts/user
Rendering user/edit
Location Load (0.000114) SELECT * FROM locations
Location Columns (0.000900) SHOW FIELDS FROM locations
Join Table Columns (0.000558) SHOW FIELDS FROM locations_users
Location Load (0.000327) SELECT * FROM locations INNER JOIN
locations_users ON locations.id = locations_users.location_id WHERE
(locations_users.user_id = 2 )

Processing UserController#update
Parameters: {“user”=>{“locations_ids”=>[“1”, “3”]}, “commit”=>“Save
Data”, “action”=>“updateLocation”, “id”=>“2”, “controller”=>“user”}
User Columns (0.001231) SHOW FIELDS FROM users
User Load (0.000087) SELECT * FROM users WHERE (users.id = 2)
Location Load (0.000133) SELECT * FROM locations
Location Columns (0.000906) SHOW FIELDS FROM locations
LocationsUser Columns (0.000687) SHOW FIELDS FROM locations_users
SQL (0.000068) BEGIN
SQL (0.000209) INSERT INTO locations_users (location_id, user_id)
VALUES(11, 2)
SQL (0.004631) COMMIT