假设我有一个像这样的模型类:
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)时,我看到:
"the description of Shoebox is not in the approved list"
而不是:
"the description of Bob is not in the approved list"
我尝试过 :name => name
、:name => :name
、:name => lambda{name}
, :name => lambda{:name}
.
我尝试创建一个辅助方法
def shoebox_name
name
end
并传递 :name => Shoesbox_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/