Use Ajax in Web applications through Rails (1)

Source: Internet
Author: User

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 mode, 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, a view is generated by using the ERB template ERB as the Ruby built-in Text Template package. HTML is similar to HTML generated by PHP or JavaServer PagesJSP code. 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 JavaScript file directories installed with the system, including Prototype. js libraries), views, models, and controllers, and even the directories that store 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, we did.) 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. It contains five fields:Name,Description,Ingredients,InstructionsAnd 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

 <%= error_messages_for 'recipe' %>
<%= start_form_tag %>
Name <%= text_field :recipe, :name %>
Description <%= text_area :recipe, :description, :rows => 3 %>
Ingredients <%= text_area :recipe, :ingredients, :rows => 3 %>
Instructions <%= text_area :recipe, :instructions, :rows => 3 %>
<%= submit_tag 'Add' %><%= end_form_tag %>

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. Then

Tag, text_field and text_area of each field, Mark 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

 <% = Javascript_include_tag: defaults %> <% = Form_remote_tag: url = >{: action => 'add _ ajax '},: complete => 'document. forms [0]. reset (); ',: update => 'counter' %>
       
     
Name

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.

The counter tag 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 isUrlIt 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.


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.