如何在验证期间将 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"
我创建了一个新的 Shoebox:
s = Shoebox.new(:description => "large", :name => "Bob")
s.valid?
但是当我查看错误(s.errors.first.message)时,我看到:
“Shoebox 的描述不在 批准名单”
而不是:
“Bob 的描述不在 批准名单”
我尝试过 :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 值?
Suppose I have a model class like this:
class Shoebox < ActiveRecord::Base
validates_inclusion_of :description, :in => ["small", "medium"],
:message => I18n.t("activerecord.errors.models.shoebox.with_name",
:name => name)
end
And some yaml:
en:
activerecord:
errors:
models:
shoebox:
with_name: "the description of %{name} is not in the approved list"
And I create a new Shoebox:
s = Shoebox.new(:description => "large", :name => "Bob")
s.valid?
But when I look at the error (s.errors.first.message), I see:
"the description of Shoebox is not in
the approved list"
and not:
"the description of Bob is not in the
approved list"
I've tried :name => name
, :name => :name
, :name => lambda{name}
, :name => lambda{:name}
.
I've tried creating a helper method
def shoebox_name
name
end
And passing :name => shoebox_name
, :name => :shoebox_name
, :name => lambda{shoebox_name}
and :name => lambda {:shoebox_name}
.
How can I get the ivar value for name to be interpolated into the string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试删除验证中的消息选项,并将 yaml 更改为:
请参阅 http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models 了解更多详情
Try removing the message option in the validation, and change your yaml to be:
See http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models for more details
您可以使用自定义验证方法来实现您想要执行的操作。所有列都可以在自定义验证器中使用:
PS:经过大量谷歌搜索后,我意识到实现自定义验证器比四处搜索要容易得多。
You can use a custom validation method to achieve what you are trying to do. All the columns are available in the custom validator:
PS: After a lot of googling around, I realized that it was much easier to implement a custom validator than search around.