Forum: Ruby on Rails How do YOU read/update HABTM?

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.
Joe (Guest)
on 2006-06-07 00:15
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
Stephen B. (Guest)
on 2006-06-07 00:27
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
This topic is locked and can not be replied to.