Reputation: 971
I have the following model.
class Ingredient < ActiveRecord::Base
UNITS = [
{ name: "Unit" },
{ name: "Teaspoon" }
]
validates :unit, inclusion: UNITS.map{|u| I18n.t(u[:name]) }
end
In the console. running the following command when the locale if :fr (french), yields the following based out of my locale file.
#Ingredient::UNITS.map{ |u| I18n.t(u[:name]) }
["Unité","Cuillère à café",]
Which is correct, however the validation fails for this, when I do the following.
Ingredient.create(quantity: 4.0, unit: "Cuillère à café")
When I manually check if the unit is included within the array, I get true. Why is this validation failing? Works correctly for english.
Upvotes: 0
Views: 127
Reputation: 107117
Validators are defined when the class is loaded for the first time and do not change later on. In your example that means that
validates :unit, inclusion: UNITS.map{|u| I18n.t(u[:name]) }
is evaluated to
validates :unit, inclusion: ['Unit', 'Teaspoon']
and will not change to another locale in a later request.
It might work to assign a lambda instead on an array, like this:
validates :unit, inclusion: { in: proc { UNITS.map { |u| I18n.t(u[:name]) } } }
Upvotes: 2