假设我有一个这样的模型类:
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}
。如何将名称的 ivar 值插入到字符串中?
最佳答案
尝试删除验证中的消息选项,并将您的 yaml 更改为:
en:
activerecord:
errors:
models:
shoebox:
description:
inclusion: "the description of %{name} is not in the approved list"
有关更多详细信息,请参阅 http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models
关于ruby-on-rails - 如何在验证期间将 ivars 插入到 Rails i18n 字符串中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5085284/