interface language selector in rails form?

Deadly 提交于 2019-12-08 08:19:45

问题


What would be the way to go on having a locale selection drop down in a form?

I have a User model with a column "lng" where I store the "en","fr", etc i18n locale strings.

My goal is to have a drop down with all the languages listed " English ", " French " and on form update it stores the correct "en", "fr" value in the user table.

What would be a way to go on this?


回答1:


You can simply use the select tag http://guides.rubyonrails.org/form_helpers.html#the-select-and-option-tags:

= form_for @user do |f|
  = f.select :lng, options_for_select([['English', 'en'], ['French', 'fr']], @user.lng)

I also suggest to move the array somewhere to the constant. For example, in its own method of model User. For example:

#models/user.rb
def self.lng_list
  [['English', 'en'], ['French', 'fr']]
end

#form
= form_for @user do |f|
  = f.select :lng, options_for_select(User.lng_list, @user.lng)

edited

In simple form you can use rails form helpers like this https://github.com/plataformatec/simple_form#wrapping-rails-form-helpers:

 = f.input :lng do
   = f.select :lng, options_for_select(User.lng_list, @user.lng)

Or you can use collection option https://github.com/plataformatec/simple_form#collections:

= f.input :lng, :collection => User.lng_list


来源:https://stackoverflow.com/questions/10862910/interface-language-selector-in-rails-form

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