views:

1471

answers:

2

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?

+2  A: 

You are looking for select or collection_select. Both can be used in form_for or fields_for blocks. There are examples on how to use them in a form_for in the documentation

Peer Allan
+3  A: 

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.

ryanb