Tutorial on using rails active resource in Ruby on rails

Time:2022-6-10

brief introduction

Today’s applications need to interoperate not only with browser based clients, but also with other applications. For interoperability, web applications usually provide a web service API. The Web Services API provides remote access to applications over a network, such as the Internet. Until recently, web service APIs also used heavy and complex soap based web service integration. This kind of web service not only has no advantages, but also takes a long time to implement. The rails framework with representative state transfer (rest) based services has a simpler and faster way to implement and use web services through active resources.

After rails has implemented restful, it is now possible to provide different content types (or representations) of a specific resource through just one rails action. This approach has the following benefits:

  • 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 the ruby language. Ruby on rails is designed to help developers develop and deploy web applications more easily and quickly. Compared with other languages and frameworks, rails framework makes several assumptions. Its purpose is to use the method of agile development to achieve rapid development.

The rails framework incorporates the following packages:

  • Active record: an object relation mapping layer, which is used for database related access and functions;
  • Action Pack: a controller and view function manager;
  • Action mailer: an email processor;
  •     Active Support
  • Active resource: provides Web services (i.e. action web services).

Web Services

Web services are application components that communicate using open protocols and can be used by other applications. Web services are simple APIs that can be accessed using HTML and executed on the remote system hosting the requested service. Web service is the key integration point of various applications written in different languages and systems on different platforms.

Rest is not a protocol; It is an architectural style of large-scale Networking software that utilizes 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 architecture describes the six constraints applied to the architecture.

On the other hand, soap is a protocol specification for exchanging structured information in the implementation of Web services in computer networks. It relies on XML as its message format and usually relies on other application layer protocols (RPC and HTTP) for message negotiation and transmission. Soap can form the basic layer of the web service protocol stack and provide a basic messaging framework for building web services on it.
Rest and soap

The following table shows some of the differences between rest and soap.

Tutorial on using rails active resource in Ruby on rails

Rest relies on a single application protocol (HTTP), several URIs, and several data formats standardized through XML. It uses mature HTTP methods (such as get and post) to command applications. Rest developers use URIs to create a common foundation so that applications use HTTP and XML to share data, rather than creating a standard machine-readable method for applications to discover and use application components on remote systems (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 with each other.

Rest proponents point out that the function of directly accessing remote programs using soap protocol will inevitably encounter interoperability problems encountered by distributed computing architectures such as DCOM and common object request broker architecture.

Active Resource

Before adopting a restful approach to the communication of web applications between server and client applications, soap and other XML-RPC forms were used to communicate through an API. The active resource introduced by rails 2 replaces the action web service. Active resources fully understand restful routing and XML representation. It is a class that maps restful resources to models in rails applications. Active resource provides tools to quickly and easily use rest based web services that comply with rails restful URI structures and protocol conventions. Active resources map responses from any eligible service to rich ruby objects. Active resource also provides all the lifecycle methods required to easily perform basic crud functions.

CRUD operations correspond to HTTP methods post, get, put and delete respectively. Moreover, active resource has a method for each of 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 retrieves and modifies its data by calling back the HTTP call to the server and parsing the XML result back into a ruby object.

Listing 1 shows an example of a minimal active resource. Suppose you have a library application, each category acts as a different client, and Indian history is one of the categories.
Listing 1 Active resource example

?
1
2
3
class IndianHistory < ActiveResource::Base
self.site = “http://indian-history.com”
end

Activeresource has the same method as active record. In the above code example, the class indianhistory is inheriting from activeresource base. In the second line, self Site holds the site value containing the URI of the indianhistory book. In this case, the URI is http://indian-history.com Suppose this URI is another rails application with the necessary model and controller actions.

Now that this class is mapped to the restful resources located by the site value, you can now manipulate the resources of the indianhistory class. To get the list of all books under Indian history, you will call its find method, which is similar to the active record find method.

?
1
>> books = IndianHistory.find (:all)

This active resource module is similar to the active record module; They have the same style.

Assuming you are looking for a book titled “Akbar”, you can use the following code:

?
1
>> books = IndianHistory.find(:all, :params => { :title => “Akbar”}}

Different from the general: conditions clause in the active record find method, this example uses: params, and the URL is get http://indian-history.com/indian_histories.xml?title=Akbar 。

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

?
1
>> IndianHistory.create (:title => “Jhansi Stories”, :amount => 233.00, :available => 0)

The above code line will use the supplied data to create an HTTP post to the controller where the code in Listing 2 exists in the create action.
Listing 2 Create

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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}
else
format.html { render :action => “new” }
format.xml { render :xml => @book.errors, :status => :unprocessable_entity}
end
end
end
 
end

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

Similarly, you can update and delete records. You have the permission and access to perform management.

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

?
1
2
3
4
5
>> book= IndianHistory.find (2)
>> book.available = 1
>> book.save
>> book = IndianHistory.find (2)
>> book.available # => 1

You updated the availability of books and saved records. There is a subtle difference between activeresource and activerecord: there are no methods save and update in activeresource.

Finally, the following statement will remove the record from the database.

?
1
>> IndianHistory.delete(2)

In addition to the basic operations described above, active resource also allows to support HTTP basic authentication by setting an HTTP header. If the user name and password are set and an error is thrown when authentication fails, the security check of the client and server connections can be completed through active resource authentication on each connection. Basic authentication can also be easily implemented.

Concluding remarks

In this article, you learned about web services, rest, soap, and rails active resource. A simple example shows you the crud operation.

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.

Recommended Today

JS generate guid method

JS generate guid method https://blog.csdn.net/Alive_tree/article/details/87942348 Globally unique identification(GUID) is an algorithm generatedBinaryCount Reg128 bitsNumber ofidentifier , GUID is mainly used in networks or systems with multiple nodes and computers. Ideally, any computational geometry computer cluster will not generate two identical guids, and the total number of guids is2^128In theory, it is difficult to make two […]