Veerasundaravel's Ruby on Rails Weblog

February 1, 2011

Rails ActiveRecord: validate single attribute


 

In Rails ActiveRecord we can validate a whole object, but we cannot validate a particular attribute of the object something like below:

>> u = User.new(:email=>"blah blah", :name=> "Some Correct Name")
>> u.valid?
>> false

>> u.valid?(:email)
ArgumentError: wrong number of arguments (1 for 0)
from (irb):2:in `valid?'
from (irb):2
>>

 

Here some quick solution for validating a particular attribute of an ActiveRecord object. Create a .rb file like below place in config\initializers folder.

module ValidateAttribute
  def self.included(base)
    base.send :include, InstanceMethods
  end

  module InstanceMethods
    def valid_attribute?(attribute_name)
      self.valid?
      self.errors[attribute_name].blank?
    end
  end
end

ActiveRecord::Base.send(:include, ValidateAttribute) if defined?(ActiveRecord::Base 

 

Now you can validate a particular attribute of an object as follows:

>> u = User.new(:email=>"blah blah", :name=> "Some Correct Name")
>> u.valid?
>> false

>> u.valid?(:email)
ArgumentError: wrong number of arguments (1 for 0)
from (irb):2:in `valid?'
from (irb):2
>>
>> u = User.new(:email=>"blah blah", :name=> "Some Correct Name")
>> u.valid?
>> false

>> u.valid_attribute?(:email)
>> false

>> u.valid_attribute?(:name)
>> true 

%d bloggers like this: