Using a field value from the active record object being saved in a custom validation message?
Rails 2.3.5
I'm having trouble figuring out if this is possible or not (Google is not my friend tonight). I have this validation (for @product.save):
validates_uniqueness_of :product_name, :scope => [:category, :catalog_id], :message => "..."
I'd like the error message to name the category to be clear. Like, say :category in this case is 'shoes'.
What I'd like is to have the开发者_JS百科 error say:
"There is already a shoes product in this catalog with the same name."
For example, I've tried:
:message => "There is already a #{:category} product in this catalog with the same name."
(result: "There is already a category product in this catalog with the same name.")
and
:message => "There is already a #{@product.catalog} product in this catalog with the same name."
(result: nil error)
Try (not tested, but one of them should work):
:message => "There is already a %{category} product ..."
:message => "There is already a %{value} product ..."
:message => "There is already a %{attribute} product ..."
If that does not work, move the message into a translation file (config/locales/en.yml
for example) and the use t()
to get the message.
Validation messages by default use the I18n api which does support interpolations.
However it can only interpolate values passed to it by the validator so the only way you can do it is by hacking the UniquenessValidator to pass it in as an option.
精彩评论