How can I interpolate ivars into i18n Rails strings during validation?

Suppose I have a model class:

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:

"Shoebox description not on approved list"

and not:

"Bob's description is not on an approved list"

I tried :name => name :name => :name :name => lambda{name} :name => lambda{:name} .

I tried to create a helper method

  def shoebox_name name end 

And the walkthrough :name => shoebox_name :name => :shoebox_name :name => lambda{shoebox_name} and :name => lambda {:shoebox_name} .

How can I get the ivar value for a name that should be interpolated into a string?

+4
source share
2 answers

Try removing the message parameter in the validation and change yaml as follows:

 en: activerecord: errors: models: shoebox: description: inclusion: "the description of %{name} is not in the approved list" 

For more information see http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models

0
source

You can use your own verification method to achieve what you are trying to do. All 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 many searches, I realized that implementing a custom validator is much easier than looking.

-1
source

Source: https://habr.com/ru/post/1340886/


All Articles