Creating a select element from an ActiveRecord class in Ruby on Rails

Ruby on Rails contains a pretty amazing tool for creating select elements from a collection. I'll show the most useful one, IMO, that allows you to take an Array of ActiveRecord objects and build a select list from it.

<% form_for(@item) do |f| %>

  <%= f.error_messages %>

  <p>
    Type of Item<br/>
    <%= f.select(:itemtype_id, Itemtype.all.collect { |it|  [it.name, it.id] }) %>
  </p>

<% end %>

This select form helper is broken down in to the following parameters. Because this is in a form for, the object property is not required, but it is normally first.

The next property is the name of the value that will be updated. If this value is an ActiveRecord association, use the actual field id, such as "itemtype_id" instead of trying to set the ActiveRecord object "itemtype".

Finally, it takes an array of values. You can use ActiveRecord to retrieve all elements into an Array. Use the built-in Array's collect or map method generate a new array of name, value pairs.

For more information, refer to the Rails Documentation page for FormOptionHelpers.

Comments

#1 Anonymous

Yeah, these things are awesome. If you find yourself repeating them, use a named scope instead.

#2 bmancini

VERY COOL. Thanks for posting a link to named scopes.

Recent comments