Rails Basics - Adding a drop down list to your forms
These "Rails Basics" blog posts are simple how-to's for Rails 3. These are aimed at beginners to Rails, but prior programming knowledge will be helpful.
Assuming you have used the scaffolding to generate your views, this example is code that resides in the _form.html.erb view. In this example, we have a table of Users and a table of Colors. Each user can have a favorite color assigned to them. This _form.html.erb view is in the Users folder.
The code used to create the drop down list is:
<%= f.collection_select(:color_id, Color.all, :id, :color_name ) %>
- :color_id is the foreign key that resides in the Users table
- :Color.all specifies which records to include in the drop down list
- :id is the primary key in the Colors table
- :color_name is the field from the Colors table to display in the drop down list
That is all there is to it, Rails will take care of pre-selecting the right option on your edit page.