views:

89

answers:

1

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.

+2  A: 

First of all, don't include ActiveModel::Validations, it's already included in ActiveRecord::Base. And secondly, you don't specify the options for a validation with an :options key, you do it with the key for your validator.

class User < ActiveRecord::Base
  validates :name,
           :is_not_reserved => { :message => 'sorry, but the name is not valid' }
end
Samuel
Thanks, Samuel. It works!
Shamaoke
And isn't it much cleaner? :)
Stephen Orr