Tutorial on using Ajax in Ruby on Rails _ruby topics

Source: Internet
Author: User
Tags html form one table ruby on rails

If you've never heard of rails, you're welcome to return from an extraterrestrial trip, and in recent years it's probably the only place that hasn't heard of Ruby on rails. The most compelling thing about Rails is the ability to quickly build a full-featured application and run it. Rails's built-in integrated Prototype.js library for Ajax makes it easy and quick to create so-called rich Internet applications.

This article walks you step-by-step through creating a Rails application. Then delve into how Ajax features can be used to write JavaScript code that reads and writes data from the server.
Easy start Ajax Tour--ajax Technology Resource Center

What is Ajax? Ajax (asynchronous JavaScript and XML) is a programming technique that allows you to combine XML and JavaScript for Web applications, breaking the paradigm of page refreshes and enabling your users to interact quickly and easily with Web applications.

Do you want to know how to build an Ajax based application? DeveloperWorks China has a lot of Ajax-related articles, tutorials, and tips, and through the Ajax Technology Resource Center, you can quickly find technical reference resources that can help you complete the development of applications associated with Ajax.

A bit of a note about Rails

So what exactly is Rails? Rails is a WEB application platform built on the Ruby programming language. Ruby has existed for about 10 years. Like Perl and Python, it is 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 pattern, the model-view-controller (MVC). Here, the model portion of the system is typically represented by a set of ActiveRecord objects mapped to database tables. The controller section is a Ruby class that can perform various operations on the model. The view is typically a Hypertext Markup Language code (HTML) generated by the ERB template (ERB is a Ruby-built text template package), similar in form to HTML generated by PHP or JavaServer Pages (JSP) code. Views can also be Extensible Markup Language (XML), text, JavaScript code, pictures, or anything else.

When a user requests a page from a Rails Web application, the URL is sent through the routing system, which sends the request to the controller. The controller requests data from the model and sends it to the view to complete the format.

When you create a Rails application, the system automatically generates some directories and basic files. Includes a JavaScript file directory (including the Prototype.js Library), a view, model, and Controller directory installed with the system, and even a directory of plug-ins that are downloaded from other developers.


start using Rails

The easiest way to create a rails application is to use a pre-packed rails system. What if the platform is Microsoft? Windows, we recommend that you use Instant Rails. I like locomotive 2 apps very much on the Macintosh machine. 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 little effort.

This article will create a new recipe application called recipe, which requires only one table. Listing 1 shows the database migration for the Recipe application.
Listing 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:d escription,: text,: null => false
 t.column:ingredients, : text,: null => false
 t.column:instructions,: text,: null => false
 end

 def Self.down
 Drop_table:recipes
 End


There is only one table in the database: recipes. Contains five fields: Name, description, ingredients, instructions, and one field is the unique identifier for automatic maintenance of the Rails infrastructure.

After you have set up your database table, you need to wrap a ActiveRecord object for it. The object is shown in Listing 2.
Listing 2. Recipe model

Class Recipe < activerecord::base
 validates_presence_of:name
 validates_presence_of:d escription
 Validates_presence_of:ingredients
 validates_presence_of:instructions
End

The ActiveRecord base class is responsible for all basic database access: Query table, INSERT, UPDATE, and delete records. Just add the validation for each field here. I told Rails. Each field cannot be empty.


Ajax Forms

The first step in creating an Recipe application is to add recipes to the database. Let's start by introducing the standard way to create a basic 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][:d escription]
 @ recipe.ingredients = params[:recipe][:ingredients]
 @recipe. Instructions = params[:recipe][:instructions]
 @ Recipe.save end end


There is only one method add, which first creates an empty Recipe object. Then, when the client makes the request, it adds parameters and saves the data.

The ERB template for the page is shown in Listing 4.
Listing 4. Add.rhml

 
 

The page first displays the error message for the recipe object. These messages are set if the user publishes data that is not validated by the Recipe model object. Then the <form> tag, Text_field and Text_area entries for each field, <submit> tags, and the end of the form are followed sequentially.

This is very standard Rails. Safe and reliable, can be used in a variety of browsers, clearly mapped to the HTML created for the client. But what I need is WEB 2.0, which means Ajax. So, how do you modify it?

The Add () method on the controller side is 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],
 :d escription => params[:recipe][:d escription], ingredients =>
 : Recipe][:ingredients],
 : Instructions => params[:recipe][:instructions]})
 End


The Add () method does nothing, because a new method Add_ajax () handles the data returned by the client.

For templates, there is no need for big changes, as shown in Listing 6.
Listing 6. The beginning part of the add.rhtml

 
 

The file begins adding the head section in HTML that contains a reference to the Rails default JavaScript file. This is the prototype.js system, which completes most of the Ajax work.

The <div> tag counter is then added to save the results returned from the Ajax request. Not very necessary, but it's also good to give users some feedback.

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 the data. The second is a complete handler, where the JavaScript code executes when the AJAX request completes. This resets the form to allow the user to enter a new menu. 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 today in database

Susan But it's not exactly. This is just an Ajax form that migrates from a standard HTML form to a Rails one. Figure 1 shows the Ajax form ready for submission.
Figure 1. Ajax Forms

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


Ajax Dynamic Search

Prototype.js provides the ability to observe fields and forms on a page. I use this feature to observe a text field where I can enter a partial menu name. The Recipescontroller search method is then run, and the output is placed 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 
 End


The index () method renders an HTML form. The Search_ajax () method finds recipes based on the search parameters and sends the data to the ERB template format. 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. Then create a form with search fields and <div> tags to hold the data returned by the search. Finally, call the Observe_form () helper method, which creates JavaScript code to watch the changes in the form and sends the form data to the Search_ajax () method. The results of the method are then placed in the recipe <div>.

The code for 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, loop through the menu list and output its name and description.

When I opened the site in the browser and entered Apple in the Address bar, I found the apple pie approach, as shown in Figure 2.
Figure 2. Ajax Dynamic Search

This is the simplest implementation. But what if you want to learn more about apple pie? Can I use Ajax to dynamically get ingredients and practices when needed? I'm glad you asked! Of course I can!


Add content to the command

Sometimes it's more friendly to let users choose to download more information than to pile it up on the page in a stiff way. Traditionally, WEB application developers use hidden <div> tags to contain information that is displayed when the user requests it. Rails provides a more graceful way of using Ajax to request data when it is needed.

The menu template in Listing 11 adds a link_to_remote () helper method call.
Listing 11. Search_ajax.rhtml

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

Link_to_remote () adds JavaScript code to the page and anchor (<a>) tags that contain the specified text. When the customer clicks the link, the page issues an AJAX request to get the new content and replace the original text.

In order to get new information, you must add a Get_extra_ajax () method for Recipescontroller. As shown in Listing 12.
Listing 12. Recipes_controller.rb

Class Recipescontroller < Applicationcontroller
 ...
 def get_extra_ajax
 @recipe = Recipe.find (Params[:id])
 render:layout=>false 
 End


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

<blockquote><%= Simple_format @recipe. Ingredients%></blockquote>
<p><%= Simple_format @recipe. Instructions%></p>

Now go back to the page and enter Apple, and you'll see the results shown in Figure 3.
Figure 3. Increased access to ingredients and practices links

When you click the 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. The details of the recipe

This Ajax pattern is handy if you have a report of a line item or detail type, because it can be time-consuming to request details of each record, and it is best to request it when needed. In addition, this technique helps to conserve screen resources.

Perhaps the most popular Web 2.0 feature is AutoComplete text fields. How else would this Ajax trip be complete?


Auto Complete fields

Rails makes building AutoComplete fields extremely simple. First, add something to the index.rhtml template. The modified version is shown in Listing 14.
Listing 14. The 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, the Text_field of the browser is also modified to close the automatic completion mechanism. The items in the Drop-down list are placed in the new <div>, which calls the Auto_complete () method. The Auto_complete () helper method creates the current contents of the Autocomplete_recipe_name () method and the recipe Name text field on the server that calls the client JavaScript code.

The Recipescontroller autocomplete_recipe_name () method searches for the name, 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 
 End


You will also need a ERB template to build the 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>

Automatically complete the system find an HTML list (<ul>) where each list item is an option. Use the CSS (or the style sheet you provided) for formatting the index.rhtml page.

To see the effect of AutoComplete, open the page in the browser, and then enter Test. I added some data to the Test menu. The result is shown in Figure 5.
Figure 5. Drop-down Auto Complete list

You can use the UP and DOWN ARROW keys to select an option and then press ENTER to select it. This copies the contents of the selection to the text field.

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

Conclusion

Needless to admit, I like Rails. I've been fascinated by it since the moment I used it. As I see it, many developers of the Web are attracted to it. Why not? Rails makes creating highly interactive Web applications a breeze.

Even if you haven't started writing a rails application, I also recommend that you download Instant rails or the locomotive application to start experimenting. You will experience a lot of fun and learn a lot of what can be used in Java? PHP or something from a Microsoft. NET application. Maybe you'll find that you want to write Rails code all the time.

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.