Forum: Ruby on Rails HABTM Question w/ checkboxes

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Clem R. (Guest)
on 2009-01-10 22:27
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:

[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 -%>
[/code]

and in my controller, I have this method that handles the updates of the
preferences:

[code]
 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
[/code]

and in my model I have this method for populating each checkbox:

[code]
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
[/code]


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
This topic is locked and can not be replied to.