How do YOU read/update HABTM?


#1

In my mind, it should work like this:

<%= select ‘item’,
‘category_ids’,
Category.find(:all).collect {|c| [c.name, c.id] },
{},
{:multiple=>true, :size=>20} %>

Then Rails should automatically populate and update HABTM on that. As it
is now, the above won’t work (I created a getter in item’s model that
returns an array of category_ids) because category_ids isn’t an array.
Also, as it is now, to work with HABTM, I have to use select_tag (with
category_ids[] name), get the category_ids manually, then do
@item.category_ids = params[:category_ids]’. Isn’t there a simpler way?
My suggestion above seems like The Way It Should Be.

Joe


#2

I use check boxes:

<% Category.find(:all).each do |category|%>
<%= check_box_tag(“item[category_ids][]”,
item.id,
@item.categories.include?(category)) %>
<% end %>

As far as i’m aware (and i think my example indicates this), you can
just set category_ids on your ‘item’ object and it’ll update on save.
In fact, you should just be able to do this:

@item = Item.find(params[:id])
@item.update_attributes(params[:item])

It’ll automagically pick up category_ids as the values for the join
table.

Hope that helps,

Steve

Joe wrote:

In my mind, it should work like this:

<%= select ‘item’,
‘category_ids’,
Category.find(:all).collect {|c| [c.name, c.id] },
{},
{:multiple=>true, :size=>20} %>

Then Rails should automatically populate and update HABTM on that. As it
is now, the above won’t work (I created a getter in item’s model that
returns an array of category_ids) because category_ids isn’t an array.
Also, as it is now, to work with HABTM, I have to use select_tag (with
category_ids[] name), get the category_ids manually, then do
@item.category_ids = params[:category_ids]’. Isn’t there a simpler way?
My suggestion above seems like The Way It Should Be.

Joe