# HABTM Question w/ checkboxes

**URL:** <https://www.ruby-forum.com/t/habtm-question-w-checkboxes/157408>\
**Category:** Rails\
**Created:** [January 10, 2009, 9:27pm UTC](https://www.ruby-forum.com/t/habtm-question-w-checkboxes/157408 "2009-01-10T21:27:11Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![clemrock](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/c57346/32.png) [@clemrock](https://www.ruby-forum.com/u/clemrock)\
**Post date:** [January 10, 2009, 9:27pm UTC](https://www.ruby-forum.com/t/habtm-question-w-checkboxes/157408/1 "2009-01-10T21:27:11Z")

</div>

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:

```auto
 <% @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:

```auto
 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:

```auto
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
