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.
<%= 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.
Recent blog posts
- Canned VirtualPC Instances for IE 6, 7, 8 on XP/Vista
- Checking assembly dependencies for .NET
- Google's Public DNS
- Server Utility Functions for Non-Web Apps
- reCAPTCHA for ASP.NET MVC that uses ModelState
- Adding a container to ValidationSummary helper in ASP.NET MVC
- Generic XML Serialization Class
- Re-throwing Exceptions in C# with InternalPreserveStackTrace
- Solving xsd generation error: 'The element .... is missing'
- Enum DropDownList in ASP.NET MVC
Recent comments
- so very helpful kenny. thank
9 weeks 2 days ago - Sorry, apparently the drupal
12 weeks 3 days ago - A better method
15 weeks 4 days ago - No Source Code?
21 weeks 2 days ago - security
31 weeks 1 day ago - Nice simple solution
1 year 15 weeks ago - That's quite an interesting
1 year 32 weeks ago - Small Complaint
1 year 33 weeks ago - NIceeee
1 year 39 weeks ago - Both the SQL Server connector
2 years 16 weeks ago
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.