Hi.
I want to have an ability to set a custom message in a model validator method to notify a user about incorrect input data.
Firstly, I set a custom validator class where I redefine the validate_each
method in that way as it recommended in rails' documentation:
# app/models/user.rb
# a custom validator class
class IsNotReservedValidator < ActiveModel::EachValidator
RESERVED = [
'admin',
'superuser'
]
def validate_each(record, attribute, value)
if RESERVED.include? value
record.errors[attribute] <<
# options[:message] assigns a custom notification
options[:message] || 'unfortunately, the name is reserved'
end
end
end
Secondary, I try to pass a custom message to the validates
method by two different ways:
# a user model
class User < ActiveRecord::Base
include ActiveModel::Validations
ERRORS = []
begin
validates :name,
:is_not_reserved => true,
# 1st try to set a custom message
:options => { :message => 'sorry, but the name is not valid' }
rescue => e
ERRORS << e
begin
validates :name,
:is_not_reserved => true,
# 2nd try to set a custom message
:message => 'sorry, but the name is not valid'
rescue => e
ERRORS << e
end
ensure
puts ERRORS
end
end
But neither of that methods works:
>> user = User.new(:name => 'Shamaoke')
Unknown validator: 'options'
Unknown validator: 'message'
Where and how can I set custom messages for custom validators?
Thanks.
Debian GNU/Linux 5.0.6;
Ruby 1.9.2;
Ruby on Rails 3.0.0.