I18n.t("activerecord.errors.model-6ren">
gpt4 book ai didi

ruby-on-rails - 如何在验证期间将 ivars 插入 Rails i18n 字符串?

转载 作者:行者123 更新时间:2023-12-02 15:29:11 26 4
gpt4 key购买 nike

假设我有一个像这样的模型类:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com