Module: ActiveResource::Validations
- Defined in:
- lib/active_resource/validations.rb
Overview
Module to support validation and errors with Active Resource objects. The module overrides 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_name
and a last_name
with a validates_presence_of :first_name, :last_name
declaration 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. # => ["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)
Class Method Summary collapse
-
.included(base) ⇒ Object
:nodoc:.
Instance Method Summary collapse
-
#errors ⇒ Object
Returns the Errors object that holds all information about attribute error messages.
-
#save_with_validation ⇒ Object
Validate a resource and save (POST) it to the remote web service.
-
#valid? ⇒ Boolean
Checks for errors on an object (i.e., is resource.errors empty?).
Class Method Details
.included(base) ⇒ Object
:nodoc:
251 252 253 254 255 |
# File 'lib/active_resource/validations.rb', line 251 def self.included(base) # :nodoc: base.class_eval do alias_method_chain :save, :validation end end |
Instance Method Details
#errors ⇒ Object
Returns the Errors object that holds all information about attribute error messages.
286 287 288 |
# File 'lib/active_resource/validations.rb', line 286 def errors @errors ||= Errors.new(self) end |
#save_with_validation ⇒ Object
Validate a resource and save (POST) it to the remote web service.
258 259 260 261 262 263 264 265 266 267 268 269 |
# File 'lib/active_resource/validations.rb', line 258 def save_with_validation save_without_validation true rescue ResourceInvalid => error case error.response['Content-Type'] when /xml/ errors.from_xml(error.response.body) when /json/ errors.from_json(error.response.body) end false end |
#valid? ⇒ Boolean
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
281 282 283 |
# File 'lib/active_resource/validations.rb', line 281 def valid? errors.empty? end |