Active resource in rails

This is a powerful feature of rails to communicate between two models in two different application running in two different server. ActiveResource:Base is the main class for mapping RESTful resources as models in a Rails application. Active Resource objects represent your RESTful resources as manipulatable Ruby objects. To map resources to Ruby objects, Active Resource  only needs a class name that corresponds to the resource name (e.g., the class User maps to the resources Products, very similarly to Active Record) and a site value, which holds the URI of the resources.

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

In order to access products.com controller you need to send the json response like i am going to call the index action so we need to write :-
def index @products = Product.all respond_to do |format| format.json { render :json => @products} end end

Now the User class is mapped to RESTful resources located at http://api.products.com:3000/products/,and you can now use Active Resource’s life cycle methods to manipulate resources. In the case where you already have an existing model with the same name as the desired RESTful resource you can set the element_name value.

class UserResource < ActiveResource::Base
  self.site = "http://api.products.com:3000/"
  self.element_name = "product"
end

For basic authentication or authorization you can add a before filter method like

class UsersController < ApplicationController

  before_filter :authenticate

  private
  
  def authenticate
    authenticate_or_request_with_http_basic('Administration') do |username, password|
      username == 'admin' && password == 'password'
    end
  end

end

In this case in order to use Active resource you need to change your model

class User < ActiveResource::Base 
   self.site = "http://admin:password@api.products.com:3000/"
end

For more info please check the rails api documentation and rails cast episode

http://apidock.com/rails/ActiveResource/Base
http://railscasts.com/episodes/95-more-on-activeresource

Comments

Popular posts from this blog

Insert Bulk data using active record import

Swap primary keys between two records in the same table in Postgres

How to add a bootstrap table with fixed header and scrollable body