Thursday, June 7, 2012

Multiple Select Combo Form for Rails

I was trying to find the way to make a dropdown combo box with multiple selection for a Rails project. There are many tips in the documentation and online, but I could not find the right way to make sure the options were initialized to their proper values when the form is created. For example, if a book already belongs to categories "fiction" and "mystery," how to make sure that those are already selected and highlighted on the form. This is what I finally arrived at. A key point is that the column name needs to be “{collection}_ids” and not simply “{collection},” in order for the right choices to be automatically selected when the form is built. This example would be used in selecting multiple categories to apply to some model.
= fields_for :record do |form|
  = form.label :category_ids, “Categories”
  = :category_ids, 
       Category.collect {|x| [,]}, {}, :multiple => true
I think the standard update action in the controller will handle this without any special action. To do the update manually, you could just say

See the Rails doc at