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 %>
<div class="search-hoods">
<input type="checkbox" name="user[sale_alerts]" value="<%=
hood.id %>" id="neighborhood_id-<%= hood.id %>" />
<%=h hood.name %>
</div>
<% 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.