diff options
author | Sukeerthi Adiga G <sukeerthiadiga@gmail.com> | 2011-08-05 13:13:31 +0530 |
---|---|---|
committer | Xavier Noria <fxn@hashref.com> | 2011-08-13 16:22:30 -0700 |
commit | 7963099b904031fef7d593d5be7e2061d1bcbfe8 (patch) | |
tree | ed5b2141390c5c75bd57b4a357d1d8578f9fadd3 /railties | |
parent | 4bde1b0041d73accf75525697461ac6b9fad5404 (diff) | |
download | rails-7963099b904031fef7d593d5be7e2061d1bcbfe8.tar.gz rails-7963099b904031fef7d593d5be7e2061d1bcbfe8.tar.bz2 rails-7963099b904031fef7d593d5be7e2061d1bcbfe8.zip |
ActiveResource::Validations module basics updated
Diffstat (limited to 'railties')
-rw-r--r-- | railties/guides/source/active_resource_basics.textile | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/railties/guides/source/active_resource_basics.textile b/railties/guides/source/active_resource_basics.textile index 332d113fa7..3294227f7b 100644 --- a/railties/guides/source/active_resource_basics.textile +++ b/railties/guides/source/active_resource_basics.textile @@ -69,6 +69,56 @@ person = Person.find(1) person.destroy </ruby> +h3. Validations + +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. + +h4. Validating client side resources by overriding validation methods in base class + +<ruby> +class Person < ActiveResource::Base + self.site = "http://api.people.com:3000/" + + protected + + def validate + errors.add("last", "has invalid characters") unless last =~ /[a-zA-Z]*/ + end +end +</ruby> + +h4. Validating client side resources + +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: + +<ruby> +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[:last_name] # => ["can't be empty"] +person.last_name = "Halpert" +person.save # => true (and person is now saved to the remote service) +</ruby> + +h4. Public instance methods + +ActiveResource::Validations have three public instance methods + +h5. errors() + +This will return errors object that holds all information about attribute error messages + +h5. save_with_validation(options=nil) + +This validates the resource with any local validations written in base class and then it will try to POST if there are no errors. + +h5. valid? + +Runs all the local validations and will return true if no errors. + h3. Changelog * July 30, 2011: Initial version by "Vishnu Atrai":http://github.com/vatrai
\ No newline at end of file |