Agile Web Development

Build it. Launch it. Love it.

acts_as_dropdown

Here is a simple example for how to use the acts_as_dropdown plugin. Assuming you have a model that contains a list of states, consider the following code:

class State < ActiveRecord::Base
  acts_as_dropdown
end

Since the plugin automatically assumes the use of the :name and :id attributes of the class for use when creating the text and value attributes of the option tags, you can now easily use the select form helper to create a dropdown of the States:

<%= select("person", "state_id", State.to_dropdown) %>

You can also customize what the to_dropdown method returns using the :value, :text, :conditions, and :order parameters (both at the class level and at the method level. For example:

class State < ActiveRecord::Base
  acts_as_dropdown
end

<%= select(&#8220;person&#8221;, &#8220;stateid&#8221;, State.to_dropdown) %>

The plugin also provides a to_dropdown method for the Array class which allows you to easily turn any array into a group of select options. Just like the ActiveRecord class method the Array method assumes the :name and :id attributes for the text and value of the option tag. For example:

@people = People.find(:all, :limit => 5, :order => &#8220;id&#8221;)

<%= select(&#8220;post&#8221;, &#8220;personid&#8221;, @people.todropdown) %>

Vitals

Home http://delynnberry.com/pages/acts_as_dropdown
Repository svn://delynnberry.com/code/plugins/acts_as_dropdown/trunk
License OpenSource
Tags Tag_red dg
Rating (15 votes)
Owner Delynn Berry
Created 18 April 2006

Comments

  • Tom
    29 October 2006

    Shouldn't this be a helper? I.e. it belongs in the view not the model.

  • Avatar
    Timothy Johnson
    9 October 2007

    could be a helper for sure, but it suits when (and only when) a particular table is really only used for dropdown purposes, like state/country selects and other possible collections.

Add a comment