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”

  1. Tim Lucas Says:
    and a sprinkling of DRY:
    
    module ActiveRecord
      class Base  
        def self.to_select(conditions=nil)
          find(:all, :conditions => conditions).to_select
        end
      end
    end
    
  2. codeninja at gmail.com Says:
    Dry and good for fields other than name.
    
    module ActiveRecord
      class Base  
        def self.to_select(index={}, conditions=nil)
          find(:all, :conditions => conditions).to_select(index)
        end
      end
    end
    
    class Array
      def to_select(index)
        self.collect { |x| [x.const_get(index),x.id] }
      end
    end
    
  3. DeLynn Berry Says:
    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.
  4. Jesper Rønn-Jensen (justaddwater.dk) Says:
    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!

Sorry, comments are closed for this article.