In the tutorial of using AJAX in Ruby on Rails, railsajax

Source: Internet
Author: User

In the tutorial of using AJAX in Ruby on Rails, railsajax

If you have never heard of Rails, you are welcome to return from an alien trip. In recent years, you have probably never heard of Ruby on Rails. The most attractive part of Rails is the ability to quickly build and run fully functional applications. Rails's built-in Prototype. js library for Ajax allows you to easily and quickly create so-called rich Internet applications.

This article will guide you step by step to create a Rails application. Then we will analyze how to use Ajax to write JavaScript code for reading and writing data from the server.
Start Ajax with ease-Ajax Technical Resource Center

What Is Ajax? Ajax (Asynchronous JavaScript and XML) is a programming technology that allows the combination of XML and JavaScript For Web applications to break the page refresh paradigm, allows your users to quickly and conveniently interact with Web applications.

Do you want to know how to build Ajax-based applications? There are a lot of Ajax articles, tutorials, and tips on the developerWorks Chinese website, through the "Ajax technical resource center ", you can quickly find technical reference resources that can help you complete Ajax-related application development.

A description of Rails

So what is Rails? Rails is a Web application platform built on the Ruby programming language. Ruby has been around for about 10 years. Like Perl and Python, it is also an open-source Agile programming language that fully supports object-oriented programming.

Rails, as an application framework, emphasizes the use of the correct Web application model, namely Model-View-controller (MVC ). Here, the system model is usually represented by a group of ActiveRecord objects mapped to database tables. The controller is a Ruby class, and its method can perform various operations on the model. Generally, the hypertext markup language code (HTML) generated by the ERB template (ERB is a Ruby built-in Text Template package) is in the form of PHP or JavaServer Pages (JSP) the HTML generated by the Code is similar. A view can also be an extensible markup language (XML), text, JavaScript code, image, or something else.

When a user requests a page from a Rails Web application, the URL is sent through the routing system, and the latter sends the request to the Controller. The controller sends the request data from the model to the view for formatting.

When creating a Rails application, the system automatically generates directories and basic files. Including the directory of JavaScript files installed with the system (including Prototype. js libraries), views, models, and controllers, and even the directory that stores the plug-ins downloaded from other developers.


Start using Rails

The simplest way to create a Rails application is to use a pre-packaged Rails system. If the platform is Microsoft? Windows ?, We recommend that you use Instant Rails. On a Macintosh machine, I like the Locomotive 2 Application very much. These applications include the Rails framework, Ruby language, Web server, and MySQL. After downloading so many things (indeed), creating a Rails application is just a breeze.

This article will create a new Recipe application called Recipe, which requires only one table. Listing 1 shows the database migration of the Recipe application.
List 1. database migration

class CreateRecipes < ActiveRecord::Migration def self.up create_table ( :recipes, :options => 'TYPE=InnoDB' ) do |t| t.column :name, :string, :null => false t.column :description, :text, :null => false t.column :ingredients, :text, :null => false t.column :instructions, :text, :null => false end end def self.down drop_table :recipes endend

There is only one table in the database: recipes. There are five fields: name, description, ingredients, and instructions, and a field is the unique identifier automatically maintained by the Rails infrastructure.

After creating a database table, you need to wrap it with an ActiveRecord object. This object is shown in Listing 2.
Listing 2. Recipe Model

class Recipe < ActiveRecord::Base validates_presence_of :name validates_presence_of :description validates_presence_of :ingredients validates_presence_of :instructionsend

The ActiveRecord base class is responsible for accessing all basic databases: querying tables, inserting, updating, and deleting records. Here, we only need to add verification for each field. I told Rails that each field cannot be blank.


Ajax form

The first step to create a Recipe application is to add recipes to the database. First, we will introduce the standard method for creating a base HTML form in Rails. As shown in the RecipesController class in listing 3.
Listing 3. Recipes_controller.rb

class RecipesController < ApplicationController def add @recipe = Recipe.new if request.post? @recipe.name = params[:recipe][:name] @recipe.description = params[:recipe][:description] @recipe.ingredients = params[:recipe][:ingredients] @recipe.instructions = params[:recipe][:instructions] @recipe.save end endend

There is only one method to add. It first creates an empty Recipe object. Then, when the client sends a request, add parameters and save the data.

The ERB template on this page is shown in Listing 4.
Listing 4. Add. rhml

The error message of the recipe object is displayed first. If the data published by the user is not verified by the Recipe model object, these messages are set. The fields are marked by <form>, text_field and text_area, <submit>, and the end of the form.

This is a very standard Rails. Secure and reliable. It can be used in various browsers to clearly map to the HTML created for the client. But what I need is Web 2.0, that is, Ajax. So how can we modify it?

The add () method on the controller has completely changed, as shown in listing 5.
Listing 5. Recipes_controller.rb

class RecipesController < ApplicationController def add end def add_ajax Recipe.create( { :name => params[:recipe][:name], :description => params[:recipe][:description], :ingredients => params[:recipe][:ingredients], :instructions => params[:recipe][:instructions] } ) endend

The add () method does not do anything, because there is a new method add_ajax () to process the data returned by the client.

The template does not need to be modified, as shown in Listing 6.
Listing 6. add. rhtml

The header section of the file is added to HTML, which contains references to the default JavaScript file of Rails. This is the Prototype. js system that completes most of Ajax work.

Then, the <div> flag counter is added to save the results returned from the Ajax request. It is not very necessary, but it is also good to give some feedback to users.

Finally, change the original start_form_tag to form_remote_tag. Form_remote_tag has several parameters, the most important of which is the url, which specifies where to send data. The second is a complete processing program, where the JavaScript code is executed when the Ajax request is complete. Here, the form is reset to allow users to enter new recipes. Then, use the update parameter to tell Rails where to send the output of the add_ajax action.

The add_ajax () method also requires a template. As shown in listing 7.
Listing 7. Add_ajax.rhtml

<%= Recipe.find(:all).length %> recipes now in database

That's all. But not exactly. This is just an Ajax form that is migrated from a standard HTML form to Rails. Figure 1 shows the Ajax form to be submitted.
Figure 1. Ajax form

The next step is more dynamic interaction, such as using Ajax for dynamic search.


Ajax dynamic search

Prototype. js provides the ability to observe fields and forms on the page. I use this feature to observe a text field where I can enter some recipe names. Run the RecipesController search method and put the output in the <div> tag below the text field. Start with the updated RecipesController, as shown in listing 8.
Listing 8. Recipes_controller.rb

class RecipesController < ApplicationController... def index end def search_ajax @recipes = Recipe.find( :all, :conditions => [ "name LIKE ?", "%#{params[:recipe][:name]}%" ] ) render :layout=>false  endend

The index () method is used to render an HTML form. The search_ajax () method searches for recipes based on search parameters and sends the data to the ERB template for formatting. The index. rtml template is shown in listing 9.
Listing 9. Index. rhtml

The JavaScript library is also included at the beginning of listing 9. Create a form with search fields and <div> tags to save the data returned by the search. Finally, call the observe_form () auxiliary method. It creates JavaScript code to observe the changes in the form and sends the form data to the search_ajax () method. Then put the result of this method in recipe <div>.

The code of the search_ajax.rhtml form is shown in listing 10.
Listing 10. Search_ajax.rhtml

<% @recipes.each { |r| %>

Because there may be multiple search results, you can traverse the recipe list cyclically and output its name and description.

When I open the site in a browser and enter apple in the address bar, I find the apple pie, as shown in figure 2.
Figure 2. Ajax dynamic search

This is the simplest implementation. But what if I want to know more about apple pie? Can I use Ajax to dynamically obtain ingredients and practices as needed? I'm glad to ask you this question! Of course!


Add content to the command

Sometimes, it is more friendly for users to choose to download more information instead of simply heap the information to the page. Traditionally, Web application developers use hidden <div> tags to include information, which is displayed when the user requests the information. Rails provides a better way to request data when needed.

The link_to_remote () auxiliary method is added to the menu template in listing 11.
Listing 11. Search_ajax.rhtml

<% @recipes.each { |r| %>

Link_to_remote () adds JavaScript code and the anchor (<a>) Tag containing the specified text to the page. When you click the link, the page sends an Ajax request to obtain the new content and replace the original text.

To obtain new information, you must add a get_extra_ajax () method for the RecipesController. As shown in List 12.
Listing 12. Recipes_controller.rb

class RecipesController < ApplicationController ... def get_extra_ajax @recipe = Recipe.find( params[:id] ) render :layout=>false  endend

In addition, a template get_extra_ajax.rhtml is required to format the information. Listing 13 shows the template.
Listing 13. Get_extra_ajax.rhtml

<Blockquote> <% = simple_format @ recipe. ingredients %> </blockquote>
<P> <% = simple_format @ recipe. instructions %> </p>

Return to the page and enter apple. The result shown in Figure 3 is displayed.
Figure 3. Added links to access ingredients and practices

When you click this link, the browser uses Ajax to retrieve additional information from the Web server and display it in that location. The result is shown in Figure 4.
Figure 4. Recipe details

This Ajax mode is very convenient if there is a report of the line item or detail type, because the request details of each record may be very time-consuming, it is best to request again when needed. In addition, this technology also helps to save screen resources.

Perhaps the most popular Web 2.0 feature is automatic completion of text fields. Otherwise, how can this Ajax journey be complete?


Automatic completion Field

Rails makes building an Automatic completion field extremely simple. First, add something to the index. rhtml template. The modified version is shown in listing 14.
Listing 14. Modified index. rhtml

The Cascading Style Sheet (CSS) section above the file is used to automatically complete the drop-down list of fields. In addition, text_field is slightly modified to disable the Automatic completion mechanism of the browser. The items in the drop-down list are placed in the newly added <div>. These items call the auto_complete () method. The auto_complete () auxiliary method creates the client JavaScript code to call the current content of the autocomplete_recipe_name () method and the recipe name text field on the server.

Search for this name in the autocomplete_recipe_name () method of the RecipesController, as shown in listing 15.
Listing 15. Recipes_controller.rb

class RecipesController < ApplicationController... def autocomplete_recipe_name @recipes = Recipe.find( :all, :conditions => [ "name LIKE ?", "%#{params[:recipe][:name]}%" ] ) render :layout=>false  endend

You also need an ERB template to create a list, as shown in listing 16.
Listing 16. Autocomplete_recipe_list.rb

<ul class="autocomplete_list"> <% @recipes.each { |r| %> <li class="autocomplete_item"><%= r.name %></li> <% } %> </ul>

The system automatically finds an HTML list (<ul>), where each list item is an option. Format the index. rhtml page with CSS (or the style sheet you provided.

To view the auto-completion effect, open the page in the browser and enter test. I added some data to the test recipe. The result is shown in Figure 5.
Figure 5. drop-down auto-Completion list

You can use the up and down arrow keys to select an option and then press Enter to select. In this way, the selected content will be copied to the text field.

Very flexible. Thanks to the Rails architecture, it makes it easy to implement.

Conclusion

Needless to say, I like Rails. I was deeply attracted to it from the moment I used it. As far as I can see, many Web developers are attracted by it. Why not? Rails makes it easy to create highly interactive Web applications.

Even if you haven't started writing a Rails application, I suggest you download the Instant Rails or Locomotive application and try again. You will have a lot of fun and learn a lot about Java? PHP or Microsoft. NET applications. You may find that you want to keep writing Rails code.

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.