Ruby on Rails Guides: Active Resource Basics

# Guides.rubyonrails.org

Skip navigation.

## Active Resource Basics

This guide should provide you with all you need to get started managing the connection between business objects and RESTful web services. It implements a way to map web-based resources to local objects with CRUD semantics.

### Chapters

1. Introduction
2. Configuration and Usage
3. Reading and Writing Data
   - Read
   - Create
   - Update
   - Delete
4. Validations
   - Validating client side resources by overriding validation methods in base class
   - Validating client side resources
   - Public instance methods

This Guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails.

### 1 Introduction

Active Resource allows you to connect with RESTful web services. So, in Rails, Resource classes inherited from `ActiveResource::Base` and live in `app/models`.

### 2 Configuration and Usage

Putting Active Resource to use is very similar to Active Record. It’s as simple as creating a model class that inherits from ActiveResource::Base and providing a `site` class variable to it:

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

Now the Person class is REST enabled and can invoke REST services very similarly to how Active Record invokes life cycle methods that operate against a persistent store.

### 3 Reading and Writing Data

Active Resource make request over HTTP using a standard JSON format. It mirrors the RESTful routing built into Action Controller but will also work with any other REST service that properly implements the protocol.

#### 3.1 Read

Read requests use the GET method and expect the JSON form of whatever resource/resources is/are being requested.

    # Find a person with id = 1
    person = Person.find(1)
    # Check if a person exists with id = 1
    Person.exists?(1)  # => true
    # Get all resources of Person class
    Person.all

#### 3.2 Create

Creating a new resource submits the JSON form of the resource as the body of the request with HTTP POST method and parse the response into Active Resource object.

    person = Person.create(:name => 'Vishnu')
    person.id  # => 1

#### 3.3 Update

To update an existing resource, ‘save’ method is used. This method make a HTTP PUT request in JSON format.

    person = Person.find(1)
    person.name = 'Atrai'
    person.save

#### 3.4 Delete

‘destroy’ method makes a HTTP DELETE request for an existing resource in JSON format to delete that resource.

    person = Person.find(1)
    person.destroy

### 4 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.

#### 4.1 Validating client side resources by overriding validation methods in base class

    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

#### 4.2 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:

    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)

#### 4.3 Public instance methods

ActiveResource::Validations have three public instance methods

##### 4.3.1 errors()

This will return errors object that holds all information about attribute error messages

##### 4.3.2 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.

##### 4.3.3 valid?

Runs all the local validations and will return true if no errors.

### Feedback

You're encouraged to help improve the quality of this guide.

If you see any typos or factual errors you are confident to patch, please clone docrails and push the change yourself. That branch of Rails has public write access. Commits are still reviewed, but that happens after you've submitted your contribution. docrails is cross-merged with master periodically.

You may also find incomplete content, or stuff that is not up to date. Please do add any missing documentation for master. Check the Ruby on Rails Guides Guidelines for style and conventions.

If for whatever reason you spot something to fix but cannot patch it yourself, please open an issue.

And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome in the rubyonrails-docs mailing list.