Tutorial on using Rails Active resource in Ruby on Rails _ruby topics

Source: Internet
Author: User
Tags http post soap representational state transfer web services ruby on rails

Brief introduction

Today's applications need to interoperate not only with browser-based clients, but with other applications as well. For interoperability, Web applications typically provide a Web service API. The Web services API provides remote access to applications through a network, such as the Internet. Until recently, the Web services API had also been integrated with heavy, complex, SOAP-based Web services, which had little merit and would take a long time to implement. The Rails framework with representational state Transfer (REST) Services has a simpler, faster way to implement and use Web services through Active Resource.

After rails has implemented RESTful, it is now possible to provide a different content type (or representation) of a specific resource with a single rails action. This approach has the following benefits:

    • The various representation states of a resource.
    • Additional support for non-browser-based HTML clients is simplified in the Controller view.
    • Interoperability between applications and with new clients.

In this article, you will learn about REST, SOAP, Rails Active Resource, and how to improve interoperability between multiple applications.

Ruby on Rails

Ruby on Rails (also known as rails or RoR) is an open source Web application framework written in Ruby language. Ruby on Rails is designed to help developers develop and deploy Web applications more easily and quickly, with several assumptions in the Rails framework compared to other languages and frameworks. The goal is to use agile development methods to achieve rapid development.

The Rails framework incorporates the following packages:

    • Active Record: An object relational mapping layer for database-related access and functionality;
    • Action Pack: A controller and view function manager;
    • Action Mailer: an email processor;
    • Active Support
    • Active Resource: Provides a Web service (that is, the Action Web service).

WEB Services

WEB services are application components that use open protocol communications and can be used by other applications. Web services are simple APIs that can be accessed using HTML and executed on a remote system that hosts the requesting service. Web services are key integration points for various applications on different platforms, written in different languages, and on different systems.

REST is not a protocol; it is an architectural style of large networking software that leverages world Wide WEB technologies and protocols. REST describes how to define and process distributed data Objects (or resources), emphasizing simple information exchange and scalability. The REST schema describes the 6 constraints applied on the schema.

SOAP, on the other hand, is a protocol specification for exchanging structured information in the implementation of Web services in a computer network. It relies on XML as its message format and typically relies on other application layer protocols (RPC and HTTP) for message negotiation and transport. SOAP can form the base layer of the Web Service protocol stack, providing the underlying messaging framework for building Web services on it.

The following table shows some of the differences between REST and SOAP.

REST relies on a single application Protocol (HTTP), several URIs, and several data formats that are normalized through XML. It uses sophisticated HTTP methods, such as Get and POST, to direct applications. The REST developer uses URIs to create a common base so that applications can share data using HTTP and XML instead of creating a machine-readable standard method for the application to discover and use the application components on the remote system (this is the method SOAP uses for Web services). REST developers use XML documents instead of application method calls to tell distributed programs how to use data from one another.

REST proponents point out that the ability to access remote programs directly using the SOAP protocol is bound to encounter interoperability issues before distributed computing architectures such as DCOM and Common Object Request Broker architecture.

Active Resource

SOAP and other XML-RPC forms are used to communicate through an API before the Web application communicates between server and client applications using the RESTful method. The Active Resource introduced in Rails 2 replaces the Action Web Service. Active Resource fully understands RESTful Routing and XML representations. It is a class that maps a RESTful resource to a model in a Rails application. Active Resource provides tools to quickly and easily use RESTful Web services that adhere to the Rails RESTful URI structure and protocol conventions. Active Resource maps responses from any qualifying service to a rich Ruby object. Active Resource also provides the full lifecycle approach that is required to easily perform basic CRUD functionality.

The CRUD operations correspond to the HTTP method POST, get, put, and DELETE respectively. Also, Active Resource has a method for each method in these HTTP methods. They receive the same parameters as CRUD, but return a hash table of the received XML. The Active Resource object is essentially the front end of the REST Web server. It gets and modifies its data by invoking the HTTP call to the server and parsing the XML results back into a Ruby object.

Listing 1 shows an example of a minimal Active Resource. Suppose there is a library application, each category as a different client, and Indian History is one of the categories.
Listing 1. Active Resource Sample

Class Indianhistory < activeresource::base
Self.site = "http://indian-history.com"

Activeresource has the same method as an Active record. In the code sample above, class Indianhistory is inheriting from Activeresource Base. In the second line, Self.site holds the site value of the URI containing the Indianhistory book. In this case, the URI is http://indian-history.com (assuming that the URI is another Rails application with the necessary model and controller actions).

Now, this class is mapped to the RESTful resource where the site value is positioned, and you can now manipulate the resources of the Indianhistory class. To get a list of all the books under Indian History, you will call its Find method, which is similar to the Active record Find method.

>> books = Indianhistory.find (: All)

This active Resource module is similar to an active record module; they have the same style.

If you're looking for a book titled "Akbar," you can use the following code:

>> books = Indianhistory.find (: All,:p arams => {: Title => "Akbar"}}

Unlike the general: Conditions clause in the Active record Find method, this example uses the:p arams, and the URL is a get http://indian-history.com/indian_histories.xml?ti Tle=akbar.

Active Resource is not limited to retrieving data. You can use all CRUD operations. In the script/console, you can use:

>> indianhistory.create (: Title => "Jhansi Stories", Amount => 233.00: Available => 0)

The preceding line of code uses the supplied data to create an HTTP POST to the controller that has the code in Listing 2 in the Create action.
Listing 2. Create

Class Indianhistorycontroller < Activeresource::base
def create
@book = Indianhistory.new (params [: Indian_ History])
respond_to do |format|
If @book. Save
Flash[:notice] = "New title added successfully" 
format.html {redirect_to (@book)}
format.xml {Render:xml => @book,: status =>: Created}
format.html {render:action => "new"}
format.xml {render:xml => @book. Errors, status =>: Unpro Cessable_entity} end end

If the book record is saved successfully, the newly created record with status code HTTP 201 will be returned and the view will be redirected with the newly created record.

Similarly, you can update and delete records, primarily with permissions and access to executive administration.

For the Update operation, use in the script/console:
Listing 3. Update

>> book= Indianhistory.find (2)
>> book.available = 1
>> book.save 
>> book = Indianhistory.find (2)
>> book.available # => 1

You have updated the availability of books and saved records. There is a slight difference between activeresource and ActiveRecord: There is no method save and update in Activeresource.

Finally, the following statement removes the record from the database.

>> Indianhistory.delete (2)

In addition to the basic operations described above, Active Resource also allows HTTP Basic authentication to be supported by setting an HTTP header. If the username and password are set and an error is thrown when authentication fails, the security checks for the client and server connections can be performed through Active Resource authentication on each connection. Basic authentication is also easy to implement.


In this article, you learned about Web services, REST, SOAP, and Rails Active Resource. A simple example shows you the CRUD operations.

The Ruby on Rails Active Resource package provides easy communication between multiple Web applications in a RESTful way. In addition to CRUD operations, it allows you to create custom actions.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.