What's the right way to fill dynamic/static dropdown menus in rails?
I've always wondered what do you guys do for filling out dropdown menus in rails, and not have the code splattered in the view. Do you guys make a pivot table? Do you make a class and add methods to return arrays?
I always wonder how other people make them work, for example the other way I need to fill a combo box with all the countries I made a class called DropDownFiller, and added a method called fill_countries that would return an array wit开发者_JAVA技巧h all the countries.
What are the best practices regarding this or how do you do it?
The helper options_for_select
takes an array of options and builds the select. From the docs:
options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
<option value="$">Dollar</option>\n<option value="DKK">Kroner</option>
options_for_select([ "VISA", "MasterCard" ], "MasterCard")
<option>VISA</option>\n<option selected="selected">MasterCard</option>
options_for_select({ "Basic" => "$20", "Plus" => "$40" }, "$40")
<option value="$20">Basic</option>\n<option value="$40" selected="selected">Plus</option>
options_for_select([ "VISA", "MasterCard", "Discover" ], ["VISA", "Discover"])
<option selected="selected">VISA</option>\n<option>MasterCard</option>\n<option selected="selected">Discover</option>
There are more detailed examples in the documentation.
Depending on how your data is set up, it can be easy to fill a list. For example:
options_for_select Country.select(:name).all.map { |c| c.name }
or for custom values
options_for_select Country.all.map { |c| [c.name, c.code] }
Something else I've seen done a few times is defining a helper method in the model that returns the correct values:
class Country
# awesome country logic goes here!
def self.array_for_select
select(:name).all.map { |c| c.name }
end
end
# a long time ago in a view far far away
options_for_select Country.array_for_select
精彩评论