So, sometimes you just need a list of options for your selects. Is there a simple gem out there that makes i开发者_Python百科t easy to use one table for all the types of options you might have in your app?
This table would likely look like:
id | type | value | label
01 | color | red | Red
02 | color | black | Black
03 | shape | circle | Circle
04 | shape | square | Square
05 | state | texas | Texas
For instance, a list of countries, a list of states, a list of colors, a list of months, etc...
Then when using a select:
select_tag :color, options_for_colors
Then it would populate the select with options with values/labels from some options table, where the rows have a type of :color.
This would be easy enough to roll on my own but I don't want to spend the time if its already built.
update
I'd like this to be a dynamic table, so the end user can add/remove items from the select options table
I always use this method,
app/models/user.rb
ROLES = %w[admin author normal]
app/views/users/_form.html.erb
<%= f.collection_select :role, User::ROLES, :to_s, :titleize %>
As of Rails 3.2, here's what I do in the initializer:
ActiveRecord::Base.class_eval do
def self.types
Rails.application.routes.routes.select do |r|
r.defaults[:action]=="index" && r.defaults[:controller]== self.name.to_s.downcase.pluralize
end.map do |r|
r.defaults[:type]
end.compact
end
end
And in routes.rb I map STI actions to parent model's controller because I'm controller savvy:
resources :derived_models, :controller => :base_model, :type => "DerivedModel"
resources :more_derived_models, :controller => :base_model, :type => "MoreDerivedModel"
Now, Model.types
will give you ["DerivedModel", "MoreDerivedModel"]
精彩评论