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

标签 ruby-on-rails internationalization interpolation

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

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/

相关文章:

ruby-on-rails - 使用 ruby​​ 生成值 1 到 31 的哈希值?

ruby-on-rails - 在 Haml::Engine 中使用 Rails 方法

ruby-on-rails - Rails 可选/:locale route

用于三线性插值的 Javascript 函数

java - Android 如何沿着手指画一条平滑线

ruby-on-rails - `bundle install` 在 EC2 实例上失败

ruby-on-rails - Rails 迁移和 PostgreSQL : separate user for migration and setting privileges for production user

Magento 2 安装语言包(nl_NL 翻译)

wolfram-mathematica - Mathematica 大表周期插值

ruby-on-rails - 在 Ruby on Rails 路由中将 url 作为参数传递