2011-02-22 18 views
4

假設我有一個這樣的模型類:如何在驗證過程中將ivars插入到Rails i18n字符串中?

class Shoebox < ActiveRecord::Base 
    validates_inclusion_of :description, :in => ["small", "medium"], 
    :message => I18n.t("activerecord.errors.models.shoebox.with_name", 
        :name => name) 
end 

和一些YAML:

en: 
activerecord: 
    errors: 
    models: 
    shoebox: 
    with_name: "the description of %{name} is not in the approved list" 

我創建一個新的鞋櫃:

s = Shoebox.new(:description => "large", :name => "Bob") 
    s.valid? 

但是,當我看着錯誤(s.errors.first.message),我看到:

「鞋櫃的描述並不 批准列表」

,而不是:

「鮑勃的描述不在 批准列表」

我已經嘗試:name => name,:name => :name,:name => lambda{name}:name => lambda{:name}

我試圖創建一個輔助方法

def shoebox_name 
    name 
end 

又路過:name => shoebox_name:name => :shoebox_name:name => lambda{shoebox_name}:name => lambda {:shoebox_name}

我怎樣才能得到名字插入字符串伊娃值?

回答

-1

您可以使用自定義的驗證方法來實現你所想做。所有列在自定義的驗證可供選擇:

validate :description_in 

def description_in 
    if !(["small", "medium"].include?(description)) 
    errors.add(:base, "The description of #{name} is not in the approved list") 
    end 
end 

PS:很多周圍的Googling後,我意識到,它以實現比四處搜尋一個自定義的驗證是容易得多。

+0

downvote的原因可能會有幫助。 – 2013-09-11 14:08:28

+0

可能是因爲i18n沒有被使用? – lulalala 2015-09-16 02:13:23