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