Rails form helpers for multiple-select list box using has_many or HABTM associations

Posted by myles Wed, 16 Jul 2008 05:20:00 GMT

I don’t usually drop Rails programming bits here, but when quickly googling I couldn’t find what I was after, so figured it’s worth dropping in here:

Back in April ‘07, Ryan Bates covered how to do this with checkboxes… but I wanted to be able to do it in a list (multiple-entry select) box.

We needed to do the following:

  • Allow a user to specify multiple values from a list box
  • Allow selection of none
  • Control the size of the list box - in this case, to 6 entries

In the view:

<%= f.collection_select :category_ids, Category.by_name, :id, :name, {:selected => @item.category_ids}, {:include_blank => true, :multiple => :true, :name => 'item[category_ids][]', :size => 6} %>

NB. You’ll notice I’m using a Rails 2.1 named_scope "by_name"… which isn’t necessary but ensures I’m working with a sorted list of values in the list box.

 

In the controller

(we need to do this as a user de-selecting all entries will result in the form sending through an empty array… hence Rails will ignore it and leave it unchanged.

def update
  params[:item][:category_ids] ||= []
  @item = Item.find(params[:id]
...#as per the rest of your Update action

 

Hope this helps you out…

 

 

Comments

Leave a comment

Comments