Habtm - controlling with checkboxes UI

I need to put an array of checkboxes on a user profile editing form to
allow users to self-select which neighborhoods they are interested in
from the available neighborhoods. But I can’t figure out the syntax to
put in the view to make the neighborhood.id’s translate into actual
Neighborhood objects that makes AR happy.

The error I am getting from the below code is “Neighborhood expected,
got String”. The Neighborhood id’s are coming in just fine, but the
update_attributes() method just sees them as strings with no meaning.
Which would be fine if it would just put them in the DB and not get all
huffy…

The list of checkboxes looks like this:

<% for hood in @hoods %>

<%=h hood.name %>
<% end %>

here is the AccountController:

profile viewing or editing

def profile
@user = current_user
@hoods = Neighborhood.find(:all, :order=>:name)
return unless request.post?

if @user.update_attributes(params[:user])
flash[:notice] = ‘your account was successfully updated.’
redirect_to :action => ‘profile’
else
render :action => ‘profile’
end
end

class User < ActiveRecord::Base
has_and_belongs_to_many :sale_alerts, :class_name => “Neighborhood”

end

Thanks a Bunch!
Sam

I had some problems in my view with the ids

I usally do this

tabel.id.to_s

and maybe you gotta go through them and convert them to integer again

params[:user][:sale_alerts].each do |i|
params[:user][:sale_alerts][i] = i.to_i
end

PS: nothing tested

On Monday 03 September 2007, Jamal S. wrote:

params[:user][:sale_alerts][i] = i.to_i

end

Hi, the problem isn’t with strings<->int, it’s with row IDs -> actual AR
objects.

I ended up adding methods to the User model as such:

def sale_alerts_hood_ids=(a)
self.sale_alerts = a.collect! { |id| Neighborhood.find(id) }
end

def sale_alerts_hood_ids
return self.sale_alerts.collect { |sa| sa.neighborhood_id.to_i }
end

and if in the view I put

<% for hood in @hoods %>
<input type=“checkbox” name=“user[sale_alerts_hood_ids][]”
value="<%= hood.id %>" <%= (@user.sale_alerts_hood_ids.include?
(hood.id))? ‘checked=“true”’ : ‘’ %> />
<% end %>

then it seems to work. But this does a lot of find() calls potentially,
and seems like kind of a PITA. Having a HABTM with this kind of UI is
pretty common, I wonder if there is a more elegant solution?

Or maybe, this is sorta elegant. Maybe there is some way to DRY it up
though in case I need to use this UI with a different combo of objects.
But that’s outside my Rails comfort zone for now.