Never been to DZone Snippets before?

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

Easy Selects in Ruby on Rails (See related posts)

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 on this post

jnewland posts on Apr 10, 2006 at 14:57
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
delynn posts on Jun 02, 2006 at 20:22
I wrapped this up into a Rails plug-in called Acts As Dropdown: delynnberry.com/articles/2006/04/12/acts-as-dropdown-plugin.

You need to create an account or log in to post comments to this site.


Click here to browse all 5059 code snippets

Related Posts