Module to support validation and errors with Active Resource objects. The module overrides ActiveResource::Base#save to rescue ActiveResource::ResourceInvalid exceptions and parse the errors returned in the web service response. The module also adds an errors collection that mimics the interface of the errors provided by ActiveRecord::Errors.

Example

Consider a Person resource on the server requiring both a first_nameand a last_namewith a validates_presence_of :first_name, :last_namedeclaration in the model:

person = Person.new(:first_name => "Jim", :last_name => "")
person.save                   # => false (server returns an HTTP 422 status code and errors)
person.valid?                 # => false
person.errors.empty?          # => false
person.errors.count           # => 1
person.errors.full_messages   # => ["Last name can't be empty"]
person.errors.on(:last_name)  # => "can't be empty"
person.last_name = "Halpert"
person.save                   # => true (and person is now saved to the remote service)
Methods
E
S
V
Instance Public methods
errors()

Returns the Errors object that holds all information about attribute error messages.

# File activeresource/lib/active_resource/validations.rb, line 286
def errors
  @errors ||= Errors.new(self)
end
save_with_validation()

Validate a resource and save (POST) it to the remote web service.

# File activeresource/lib/active_resource/validations.rb, line 258
def save_with_validation
  save_without_validation
  true
rescue ResourceInvalid => error
  case self.class.format
  when ActiveResource::Formats[:xml]
    errors.from_xml(error.response.body)
  when ActiveResource::Formats[:json]
    errors.from_json(error.response.body)
  end
  false
end
valid?()

Checks for errors on an object (i.e., is resource.errors empty?).

Examples

my_person = Person.create(params[:person])
my_person.valid?
# => true
my_person.errors.add('login', 'can not be empty') if my_person.login == ''
my_person.valid?
# => false
# File activeresource/lib/active_resource/validations.rb, line 281
def valid?
  errors.empty?
end