handy select functions
Courtenay : April 9th, 2006
Sick of making select boxes from models in rails? Vomit no further!
Throw this into a lib someplace.
module ActiveRecord
class Base
def self.to_select(conditions = nil)
find(:all).collect { |x| [x.name,x.id] }
end
end
end
class Array
def to_select
self.collect { |x| [x.name,x.id] }
end
end
Now you can do something like
<%= form_for 'monkey', @monkey do |f| %>
<%= f.select 'user_id', User.to_select %>
<% end %>
Bliss!
3 Responses to “handy select functions”
Sorry, comments are closed for this article.
April 9th, 2006 at 11:30 PM and a sprinkling of DRY:
April 10th, 2006 at 01:43 AM Dry and good for fields other than name.
April 12th, 2006 at 06:19 AM Great suggestion, courtney! I had been creating class methods in my models to do exactly this, but your solution is **much** easier. After using it though, I felt it could be even easier to put everything into a plugin. Feel free to read about my attempt over at my weblog. I'm interested in your feedback.
April 16th, 2006 at 12:08 AM Forgive me my stupidity, but which file do I put it in? Where does it fit in? And if I want to put it in a separate file, where would it be the natural place to put that file? And how do I reference that file? Please point me to that information, if you can help. Thanks!