Create select tag from validation options using I18N

Is it possible to create a select tag from model validation without problems with I18N?

For example, if I had a model like this:

Model:

class Coffee < ActiveRecord::Base SIZES = [ "small", "medium", "big" ] validates :size, :inclusion => { :in => SIZES, :message => "%{value} is not a valid size" } end 

the form:

 <%= f.label :size %><br /> <%= select(:coffee, :size, Coffee::SIZES.collect {|d| [d, d]}) %> 

How can I make this language independent?

+4
source share
2 answers

If you are trying to make the i18n verification message independent, you donโ€™t really need to indicate which size is invalid, just like that. You submit the HTML selection form if they chose a different size, it is more likely that they were messing around with something, so an exact error message is not required.

For the highlighted text itself, you can simply pass it to the i18n system and process it. By creating an array using Coffee::SIZE.collect {|d| [t(".#{d}"), d]} Coffee::SIZE.collect {|d| [t(".#{d}"), d]} , you can add small , medium , big to your i18n file for this view to get localized values โ€‹โ€‹based on your verification parameters.

+4
source

The best way to handle this is to have language independent values โ€‹โ€‹in the database and localized labels in the user interface. You can achieve this by changing the options for your choice as follows:

 <%= select(:coffee, :size, Coffee::SIZES.collect {|d| [I18n.t(d), d]}) %> 

and having this in your locale file:

 some-language: small: "small-translation" medium: "medium-translation" big: "big-translation" 

This will generate html as follows:

 <select name="coffee[size]"> <option value="small">small-translation</option> <option value="medium">medium-translation</option> <option value="big">big-translation</option> </select> 

The user will see the localized parameters in select, but locale-dependent values โ€‹โ€‹will be published in requests, so your check will work as it should.

+5
source

Source: https://habr.com/ru/post/1392097/


All Articles