rails: fields_for select

intargc picture intargc · Aug 9, 2009 · Viewed 12.7k times · Source

In a view that I have, I am using fields_for to display form data for a relational table. However, part of this form will have select lists to choose from. I see there are label, text_field, text_area helpers for the form_for and fields_for helpers that will fill in the info needed from an already populated model object... but what about a select list helper that will do the same?

This would be particularly useful for when I have a one-to-many relationship since fields_for iterates through each item that is already in the model object and displays it with an index.

Does anything like this exist?

Answer

ryanb picture ryanb · Aug 10, 2009

There are several select helper methods which you can use. The most common being collection_select. This is great if you have a belongs_to association on the model and you want to use a select menu to set this.

<%= f.collection_select :category_id, Category.all, :id, :name %>

For other situations there is the more generic select method. Here you can supply an array of options you want to provide.

<%= f.select :priority, [["Low", 1], ["Medium", 2], ["High", 3]] %>

The first value in each array element is the name of the select option, the second is the value which will be assigned to the attribute.

There are many other select menus (for dates and times) but the above two should cover most situations. These methods work on both form_for or fields_for.