Dynamically Generate a Selection List in a Rails Template - Work with Ajax and Ruby on Rails
(Page 2 of 4 )
In a Rails application, a controller component takes charge of the views that the web user sees. The controller component is located inside the <web-app-root>/app/controllers directory. Using http://localhost:3000/hacks/ as an example, the framework looks in <web-app-root>/app/ controllers/hacks_controller.rb for an action or method namedindexthat generates the response. Actions start out as Ruby methods within a controller object (a class, in object-oriented terms) defined in this file.
The entire path on my Mac OS X machine is ~/Rails/Energy/app/controllers/ hacks_controller.rb. Energy is the top-level directory of the web application.
Let’s take a look at hacks_controller.rb for theindex()method:
class HacksController < ApplicationController
def index
end
#rest of class definition...
end
Nothing happening there; it’s an empty method definition. In this case, Rails looks for a template named index.rhtml in the app/views/hacks directory.
One of the intuitive aspects of the Rails framework is that the framework maps URL path information, such as the hacks part of http://localhost:3000/hacks, to directories of the same name in sensible locations, such as views.
index.rhtml provides the template for our hack:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<%= javascript_include_tag :defaults
%>
<title>Ajax Rails & Select lists</title>
</head>
<body>
<%= form_remote_tag(:update => "sel_con",:url => { :action => :create_select
},
:position => "top",:success => "$('sel_con').innerHTML=''" ) %>
<p>
Please select a sports category:
</p>
<p>
<%= select_tag "categories",
"<option>Team</option><option> Individual</option>" %>
</p>
<div id="sel_con"></div>
<p>
<%= submit_tag "Show Sports" %>
</p>
<%= end_form_tag %>
</body>
</html>
This template calls the form_remote_tag() method to update the div positioned beneath theformtag. This method wraps all of the Ajax- and request object–related functionality, updating thedivwith server data and positioning any more information on top of or before any existingdivcontent (as specified by the:position => "top"parameter). In other words, when the user clicks the Show Sports button, anXMLHttpRequestobject is created, and itssend()method sends a request to a Rails action namedcreate_select. This action is defined as a Ruby method in the hacks_controller.rb file we peeked at before.
Thecreate_selectaction renders the HTTP response, which specifies the tags and content of a new pop-up orselectlist. Figure 7-10 shows the result of clicking the Show Sports button.

Figure 7-10. Voila, up pops a select list
Next: Rendering the HTTP Response >>
More JavaScript Articles
More By O'Reilly Media
|
This article is excerpted from hack 58 of the book Ajax Hacks, written by Bruce W. Perry (O'Reilly; ISBN: 0596101694). Check it out today at your favorite bookstore. Buy this book now.
|
|