Making <select> <option> dropdowns in Ruby on Rails
March 27th, 2007 by Leons PetrazickisThere 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
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) %>
<%= select("MyModelTable", "MyColumn", MyModel.MyList) %>
The list will now show up as a dropdown. When editing, the appropriate value will be selected.
References:
Posted in ruby |




March 27th, 2007 at 13:17
This is interesting… In Bloglines, the title of your post actually creates a single option dropdown. Was that intentional?
March 27th, 2007 at 14:27
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.