DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

John has posted 11 posts at DZone. View Full User Profile

Easy Selects In Ruby On Rails

04.10.2006
| 4150 views |
  • submit to reddit
        Via http://habtm.com/articles/2006/04/10/handy-select-functions

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
    

Comments

Snippets Manager replied on Mon, 2006/01/23 - 6:05am

I wrapped this up into a Rails plug-in called Acts As Dropdown: delynnberry.com/articles/2006/04/12/acts-as-dropdown-plugin.

Snippets Manager replied on Mon, 2012/05/07 - 2:22pm

DRY-ified (from the comments of that same page): 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