Hello,
I have an address table that has a HABTM relationship w/ a
preferences table. I want to set the preferences table to handle a
variety of preferences for each address. For instance, for each
address the preferences table could carry values for make_private = t/f,
report_updates=t/f ect.
In my view where I set each value I have this code:
<% @addresses.each_with_index do |address, index| %>
<tr class="<%=cycle('odd', 'even') %>">
<td width="10">
<%=check_box("address", address.id,
address.has_update_preference?(address.id)=='1' ? {:checked=>'checked'}
: {:checked => ''}) %>
</tr>
<% end if @addresses -%>
and in my controller, I have this method that handles the updates of the
preferences:
def save_preferences
unless params[:address].nil?
params[:address].each do |key,val|
pref = Preferences.find(:first,:conditions=>["address_id=? &&
preference_name='notify_update'",key])
if pref.nil?
pref = Preferences.new(:address_id =>key,
:preference_name=>'notify_update', :preference_value => val)
pref.save
else
pref.update_attributes(:address_id =>key,
:preference_name=>'notify_update', :preference_value => val)
end
end
end
end
and in my model I have this method for populating each checkbox:
def has_update_preference?(id)
update_preference = Preferences.find(:first,
:select=>["preference_value"],:conditions=>["preference_name='notify_update'
&& address_id=?", id])
unless update_preference.nil?
return update_preference[:preference_value]
else
return 0;
end
end
That’s a lot of database calls for each checkbox, it seems rails would
have a more glorious way of doing this.
I would also like to extend this address preferences concept to handle
preferences on individual address fields
IE address.email = preferences.email_public_private t/f
Any suggestions?
Thanks,
Eric