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
Awesome..
Comment by Srikanth — February 2, 2011 @ 1:26 pm
i love it
Comment by facebook — February 17, 2011 @ 8:19 pm
It is very useful for me.
Comment by palpandi — February 23, 2011 @ 12:48 pm
Thanks for this solution :)
Comment by Gerd — October 30, 2012 @ 2:42 pm