0

I have three models: User, FavCategory, and Category. Obviously the FavCategory DB table is nothing more than an association table.

I currently do not have this setup as a HABTM association, because I'm only needing to reference the favorite categories with the current user.

# User.rb
has_many :fav_categories

# FavCategory.rb
belongs_to :user
belongs_to :category

Now I'm wanting to allow the user to choose from checkboxes and select this categories they want as their favorites, I currently have this:

<div class="field">
  <%= f.label 'Fav Categories' %>
  <ul>
    <% Category.all.each do |c| %>
      <li>
        <%= check_box_tag 'user[fav_category_ids][]', c.id, @user.fav_categories.pluck(:category_id).include?(c.id) %>
        <%= c.title %>
      </li>
    <% end %>
  </ul>
  <% end %>
</div>

So my questions are:

  1. Should I use HABTM? Or is it not necessary?
  2. If HABTM isn't necessary, how would I name the checkboxes in order for them to update the user's fav categories upon saving?

Thanks!

Wes Foster
  • 8,770
  • 5
  • 42
  • 62

2 Answers2

1

1) I wouldn't use HABTM here only because my first thought was "i bet at some point a user is going to want to custom order their favorite categories." and once they ask that you need that intermediary table to add ranking/position information to.

2) I think what you've got there is right, but it's been a long time since I manually created field names... why aren't you using form_for @user and it's goodness?

Philip Hallstrom
  • 19,673
  • 2
  • 42
  • 46
1

I think you should don't use HABTM. You will never know when you need to add some columns for FavCaterogy, and if you need, you can't add. You should use has_many :through association, it create a join Model, so you can add more columns after if you need.

Also, if you want to do some statistics, example, if you want to find: the number of users of a favorite category, it will be easy if you have a join Model, just use count method of model. With HABTM, you can not do it.

How to create form? You can take a look guide for form helper.

Thanh
  • 8,219
  • 5
  • 33
  • 56
  • How would I name the checkbox tag in order for it to update in the user model? That's what getting me the most. I've worked with normal forms and HABTM forms, but this one is tricky. Not really sure where to look in the guide for this type of situation. – Wes Foster Nov 19 '12 at 23:55
  • what do you mean `name the checkbox tag`? You can get a list category and display as checkbox list on form, isn't it? – Thanh Nov 20 '12 at 03:33