Customise message for validates_uniqueness_of

70 views
Skip to first unread message

Ricky Hopkins

unread,
Jul 25, 2014, 11:21:08 PM7/25/14
to rubyonra...@googlegroups.com
I am trying to convert an integer to a DAYNAME in my validation message

validates_uniqueness_of :day, scope: :store, :message => "already has a target for #{Date::DAYNAMES[self.day]}."

This does not seem to work, I cannot access the day value.
The following displays the correct value

validates_uniqueness_of :day, scope: :store, :message => "already has a target for %{value}."

This throws an error:

validates_uniqueness_of :day, scope: :store, :message => "already has a target for #{Date::DAYNAMES[%{value}]}."


Any help would be Amazing!

Matt Jones

unread,
Jul 28, 2014, 8:43:00 AM7/28/14
to rubyonra...@googlegroups.com
Using double quotes with #{} will *definitely* not do what you want; the interpolation will be attempted at class-load time, not when the string is needed.

The value passed to :message is handed off to I18n.translate, so the docs for that may be some help.

It may be easier (and clearer) to just define a custom validation function that does what you want.

--Matt Jones

Eric Saupe

unread,
Jul 28, 2014, 4:55:54 PM7/28/14
to rubyonra...@googlegroups.com
This is along the lines of what Matt is referring to.

class DayValidator < ActiveRecord::Validator
 
def validate()
   
if YOUR_TEST_FOR_INVALIDITY(record.day)
      date
= Date::DAYNAMES[record.day]
      record
.errors[:day] << "already has a target #{date}"
   
end
 
end
end

class YourClass < ActiveRecord::Base
  validates_with
DayValidator
end
Reply all
Reply to author
Forward
0 new messages