Create a flexible, localized, Ruby-on-Rails list-of-values

做~自己de王妃 提交于 2020-01-22 08:10:23

问题


I have a list of values (Beginner, Intermediate, Advanced, Fluent, Native) that I would like to:

  • act as the model for a SELECT list
  • act as a model to convert ids to values in a HTML table
  • use in multiple controllers and views
  • keep in an order that preserves the business rules (ordered by skill level)
  • localize at some point in the future

Is there a way of implementing this list to address all or most of my needs?


回答1:


You can put the definition of an array in /config/locales/some_language.yml

for example you could have the following in en.yml

en:
   experience_levels: 
          1: Beginner 
          2: Intermediate
          3: Advanced 
          4: Fluent
          4: Native

To get the key value pairs into a helper, the following should work:

def experience_levels 
    I18n.t(:experience_levels).map { |key, value| [ value, key ] } 
end

To use this in a select box,you would just put the following in your form_for

<%= f.select :experience_levels, experience_levels %>

If you are using form_tag instead you need the following:

<%= select_tag :experience_levels, options_for_select(experience_levels) %>


来源:https://stackoverflow.com/questions/2405047/create-a-flexible-localized-ruby-on-rails-list-of-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!