Download DB2

Making <select> <option> dropdowns in Ruby on Rails

March 27th, 2007 by Leons Petrazickis

There is a simple way to make a drop-down list of constants in a Rails form. Such lists are needed for months, provinces, weekdays, and other enum-like concepts. You don’t need to mess around with multiple tables and the corresponding belongs_to, has_one, has_many, and has_and_belongs_to_many relations.

First of all, add your list to your model in app/models/:

class MyModel < ActiveRecord::Base
        def self.MyList
                ["British Columbia",
                "Alberta",
                "Saskatchewan",
                "Manitoba",
                "Ontario",
                "Quebec",
                "Nova Scotia",
                "New Brunswick",
                "Prince Edward Island",
                "Newfoundland and Labrador",
                "Nunavut",
                "Northwest Territories",
                "Yukon"]
        end
end
 

Then, change the Province textbox in app/views/MyView/_form.rhtml to:

<p><label for="MyModelTable_MyColumn">MyColumn</label>
<%= select("MyModelTable", "MyColumn", MyModel.MyList) %>
 

The list will now show up as a dropdown. When editing, the appropriate value will be selected.

References:

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • digg
  • Reddit

Posted in ruby |

2 Responses

  1. Pythor Says:

    This is interesting… In Bloglines, the title of your post actually creates a single option dropdown. Was that intentional?

  2. Leons Petrazickis Says:

    Not intentional. I surmise that, because there are so many conflicting ways feeds encode their HTML content, Bloglines might be a bit too lenient in their decoding. In fact, one wonders if it would do the same for a script tag.

    Some feeds use plain text, some use unescaped HTML, some use escaped HTML, some use doubly escaped HTML. A robust feed reader has to handle all of them.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.