How can i interpolate ivars into Rails i18n strings during validation?
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 ya开发者_开发问答ml:
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?
Try removing the message option in the validation, and change your yaml to be:
en:
activerecord:
errors:
models:
shoebox:
description:
inclusion: "the description of %{name} is not in the approved list"
See http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models for more details
You can use a custom validation method to achieve what you are trying to do. All the columns are available in the custom validator:
validate :description_in
def description_in
if !(["small", "medium"].include?(description))
errors.add(:base, "The description of #{name} is not in the approved list")
end
end
PS: After a lot of googling around, I realized that it was much easier to implement a custom validator than search around.
精彩评论