interface language selector in rails form?

2019-06-03 16:19发布

问题:

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