Flowdock

Module to allow validation of Active Resource objects, which creates an Errors instance for every resource. Methods are implemented by overriding Base#validate or its variants Each of these methods can inspect the state of the object, which usually means ensuring that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression and so on).

Example

  class Person < ActiveResource::Base
     self.site = "http://www.localhost.com:3000/"
     protected
       def validate
         errors.add_on_empty %w( first_name last_name )
         errors.add("phone_number", "has invalid format") unless phone_number =~ /[0-9]*/
       end

       def validate_on_create # is only run the first time a new object is saved
         unless valid_member?(self)
           errors.add("membership_discount", "has expired")
         end
       end

       def validate_on_update
         errors.add_to_base("No changes have occurred") if unchanged_attributes?
       end
  end

  person = Person.new("first_name" => "Jim", "phone_number" => "I will not tell you.")
  person.save                         # => false (and doesn't do the save)
  person.errors.empty?                # => false
  person.errors.count                 # => 2
  person.errors.on "last_name"        # => "can't be empty"
  person.attributes = { "last_name" => "Halpert", "phone_number" => "555-5555" }
  person.save                         # => true (and person is now saved to the remote service)
Show files where this module is defined (1 file)
Register or log in to add new notes.
October 1, 2009
0 thanks

ActiveResource validation is a little different

Given the following model on the remote end:

class Person < ActiveRecord::Base
 validates_presence_of :first_name, :last_name, :email
end

And this ActiveResource on the client end:

class Person < ActiveResource::Base
 self.site = "http://api.people.com:3000/" 
end

Validation messages will only be returned after an attempted save call on the client end - eg:

person = Person.new( :first_name => 'Billy', :emails => "william@anotherplanet.co.za" )
person.valid?                 # => true
person.errors.full_messages   # => []
person.save                   # => false
person.valid?                 # => false
person.errors.full_messages   # => ["Last name can't be empty"]

In ActiveResource::Base it is suggested that you can perform client site validation with something like this:

class Person < ActiveResource::Base
 self.site = "http://api.people.com:3000/"
 protected
  def validate
   errors.add("last name", "can't be empty") if last_name.blank?
  end
end