0

我有以下模型。在Rails 4.0中驗證I18n的包含失敗

class Ingredient < ActiveRecord::Base 
    UNITS = [ 
      { name: "Unit" }, 
      { name: "Teaspoon" } 
    ] 
    validates :unit, inclusion: UNITS.map{|u| I18n.t(u[:name]) } 
end 

在控制檯中。在區域設置爲if(frrench)時運行以下命令,根據我的語言環境文件生成以下命令。

#Ingredient::UNITS.map{ |u| I18n.t(u[:name]) } 
["Unité","Cuillère à café",] 

哪一個是正確的,但是當我做以下操作時,驗證失敗。

Ingredient.create(quantity: 4.0, unit: "Cuillère à café") 

當我手動檢查單元是否包含在數組中時,我會變爲true。爲什麼這個驗證失敗?適用於英語。

回答

2

驗證器是在類首次加載並且稍後不更改時定義的。在您的例子這意味着

validates :unit, inclusion: UNITS.map{|u| I18n.t(u[:name]) } 

進行評估,以

validates :unit, inclusion: ['Unit', 'Teaspoon'] 

並且將變化到另一個區域在以後的請求。

它可能工作到陣列上,而不是分配拉姆達,像這樣:

validates :unit, inclusion: { in: proc { UNITS.map { |u| I18n.t(u[:name]) } } }