Search code examples
ruby-on-rails-3custom-validators

Options for validates_with


I'm not able to access the values, passed as option in 'validates_with'

My model:

    class Person < ActiveRecord::Base
    include ActiveModel::Validations
    attr_accessible :name, :uid

    validates :name, :presence => "true"
    validates :uid, :presence => "true"
    validates_with IdValidator, :attr => :uid

My Custom Validator:

    Class IdValidator < ActiveModel::Validator

    def validate(record)
    puts options[:attr]
    ...
    ...
    end
    end

For testing purpose, I'm printing "options[:attr]" and all I see is ":uid" in the terminal and not the value in it. Please help!


Solution

  • When you pass in :attr => :uid, you're just passing in a symbol. There's no magic happening here—it just takes the hash of options you've attached and delivers it as the options hash. So when you write it, you see the symbol you've passed.

    What you probably want is

    Class IdValidator < ActiveModel::Validator
      def validate(record)
        puts record.uid
        ...
        ...
      end
    end
    

    Because validates_with is a class method, you can't get the values of an individual record in the options hash. If you are interested in a more DRY version, you could try something like:

    class IdValidator < ActiveModel::Validator
        def validate(record)
          puts record[options[:field]]
        end
    end
    
    
    class Person < ActiveRecord::Base
      include ActiveModel::Validations
      attr_accessible :name, :uid
    
      validates :name, :presence => "true"
      validates :uid, :presence => "true"
      validates_with IdValidator, :field => :uid
    end
    

    Where you pass in the name of the field you want evaluated.