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 
Advertisements

4 Comments »

  1. Awesome..

    Comment by Srikanth — February 2, 2011 @ 1:26 pm

  2. i love it

    Comment by facebook — February 17, 2011 @ 8:19 pm

  3. It is very useful for me.

    Comment by palpandi — February 23, 2011 @ 12:48 pm

  4. Thanks for this solution :)

    Comment by Gerd — October 30, 2012 @ 2:42 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: