Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate select tag from validation options with I18N

Is it possible to create a select tag from the models validation without having 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

Form:

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

How can I make this language independent?

like image 882
Mark Avatar asked Jan 18 '23 17:01

Mark


2 Answers

The best way to handle that is to have locale-independent values in DB and localized labels on UI. You can achieve that by changing options for your select like that:

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

and having that in you locale file:

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

That will generate html like that:

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

User will see localized options in select, but in request parameters locale-independent values will be posted, so your validation will work as it should.

like image 182
KL-7 Avatar answered Feb 03 '23 15:02

KL-7


If you're trying to make the validation message i18n independent, you don't actually need to mention which size is invalid, just that it is. You're passing an HTML select form, if they chose another size it's more likely they're messing with something so an exact error message is unnecessary.

For the select text itself, you could just pass it to the i18n system and handle it in that. By building the array with Coffee::SIZE.collect {|d| [t(".#{d}"), d]} you could add small, medium, big to your i18n file for that view to get localized values based off your validation options.

like image 45
Zachary Anker Avatar answered Feb 03 '23 15:02

Zachary Anker