Rails ActiveRecord: validate single attribute

Nikita Fedyashev picture Nikita Fedyashev · Jan 26, 2011 · Viewed 18.6k times · Source

If there is a way I can validate single attribute in Rails?

Something like:

ac_object.valid?(attribute_name)

I'm gonna use it for AJAX validation of particular model fields. Moving these validations to the Javascript makes code really ugly.

Answer

egze picture egze · Jan 26, 2011

You can implement your own method in your model. Something like this

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

Or add it to ActiveRecord::Base