Rails drop down lists

Sometimes you want to have a drop down list in your Rails application that contains both the items from a collection of model instances and some other items that are not coming from the collection.

One can combine the results of options_from_collection_for_select and options_for_select to create this. Let’s say we want to have a form with a drop down list box where we can select a category of products to display. We also want this drop down list to include an option for uncategorized products. The problem is that this option is not a real category.

We can do the following to provide that functionality. First look at the second gist which is the code for the View:

If we had three categories, for example Salads, Pizzas, and Drinks, we would get the following list:

  • [Uncategorized]
  • Salads
  • Pizzas
  • Drinks

The first option is [Uncategorized] and this comes from calling options_for_select. The rest of the options come from calling options_from_collection_for_select.

Now when that form is submitted, we can examine (see the first gist) what was selected by the user and act accordingly.

Leave a Reply