Rails & Ajax Module 5
Introduction to Rails
Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the Model-View-Controller architecture Model classes are the data classes, including constraint enforcement View classes present the data to the user Controller classes perform computations and deal with user interaction Rails uses an Object-Relational Mapping approach to working with databases A cars table corresponds to a car class The rows of the table correspond to instances of the class The correspondence is built automatically by the Rails framework Rails uses a combination of Ruby code and template files to create responses
Developer Tasks Design and build the model, including a database for storing model data Design and implement actions Design and implement the views
Document requests The Rails framework provides much of the superstructure necessary for a web application Scripts with the Rails framework set up the basic structure The first Rails example serves a single static document
Project Setup The InstantRails package provides all the components needed to develop and test Rails projects on a Microsoft Windows platformInstantRails Start the InstantRails console InstantRails Set up a rails application rails rails1 Generate a controller ruby script/generate controller say Run the default server ruby script/server The server runs for a particular application
Project Directory Structure
Project Components A controller class, SayController, in the controllers directory The controller class has method named hello An html template file (static for this example) named hello.rhtml in directory views\say The Rails framework associates these components by the name ‘say’
Request Processing
Dynamic Documents The next example displays the greeting but also displays the current time Uses Time.now from the Ruby library embeds Ruby code in template files causes the value of the executed code to be inserted in place Instance variables of the controller class can be accessed in the template file
Setting Up the Applications A controller home is created An empty action method the_form is created A static template file the_form.rhtml is created to display the initial data entry form The action on the form is simply “result” which links to an action method named result in the same controller class
The Controller and the View Action method result in the controller class Get form data Compute results Object params holds the form data in a hash-like object Can be indexed by symbols or by strings using widget names params[:phone] gets the phone number params[:unpop].to_i gets the unpopped amount as an integer The sprintf method can be used to format data Used with format specification %5.2d to format floating numbers with exactly two decimal places
Building the Database A database is created with four tables using MySQL commands A script file is used to make the typing easier Tables are named with plural names because of Rails names corresponding classes with the singular Model classes are created ruby script/generate model corvette Directives in the model files specify the table relations has_many belongs_to
Building the Application A table object gives access to the data in the table Method count gives the number of rows Method find is used to search Method find One parameter is a primary key search. The matching row is returned Parameter :all requires a second parameter giving the value of the :conditions symbol, a test condition. All matching rows are returned Parameter :first requires a second parameter giving the value of the :conditions symbol, a test condition. The first matching row is returned Method find_by_sql takes an SQL SELECT command The action methods query the database and put results into instance variables The matching template displays the results
Layouts A layout template provides a standard template for other templates Put in the layouts directory Put a layout command in the ApplicationController class The layout template can provide header and styling directions while other templates provide content variable in the layout template provides the content from the other template
AJAX
Overview of Ajax Ajax is not an API or a programming language Ajax aims to provide more responsive web applications In normal request/response HTTP cycles, the browser locks waiting for the response and an entire page must be displayed With Ajax, asynchronous requests may be made and responses are used to update part of a page User can continue to interact with a page while the request is in progress Less data needs to be transmitted Page update is quicker because only a part of a page is modified
Approaches to Ajax The iframe element can be hidden and it allows asynchronous requests to a server Javascript support allows updating other elements of the page from the frame response Microsoft introduced the XmlDocument and XMLHTML objects which are used to make asynchronous requests directly from JavaScript Other browsers followed this path Most browsers now name the object XMLHttpRequest
The Form Document The trigger for the request is a blur event on the zip code widget this.value is used by the handler to get the zip code value entered All relevant widgets have the id attribute set for easy access in the JavaScript
The Request Phase Two functions blur event handler Response processor An XMLHttpRequest object is used to create the request A callback is a function called when a response is received Function receivePlace is the callback The function name is assigned to a property of XMLHttpRequest The open method sets up the request Method parameter, either “GET” or “POST” URL parameter with zip code in the URL A parameter signifying asynchronous or not The send method sends the request The getPlace method implements this
The Receiver Phase The function that parses the response must have access to the XMLHttpRequest object This cannot be global since there may be multiple outstanding requests at any time The callback becomes an anonymous function which is defined in the getPlace method and keeps references to the XMLHttpRequest object held in a local variable The response handler only acts if the readyState is 4, meaning the response is complete
Cross-Browser Support Older Microsoft browsers uses a different approach to getting the request object Testing the existence of window.XMLHttpRequest differentiates the browsers In the older browsers new ActiveXObject(“Microsoft.XMLHTTP”) creates the object needed
Rails with Ajax The prototype JavaScript library is integrated into Rails Rails and Ajax have some limitations Not all elements can be modified, depending on the browser The div element can be modified Rails and Ajax process Sequence is triggered Data is sent asynchronously to an action handler The action handler creates a response JavaScript in the browser interprets the response
Triggering Ajax Ruby provides methods to set up triggers for Ajax processing link_to_remote triggers when a link is activated observe_field is triggered when a widget is changed Method observe_field Takes the name of the widget as a first paramater Several ‘keyword’ parameters :url where to post, often associated with an :action symbol definition :update associated to the id of the elment whose value is to be changed in response :with specifies a parameter for the HTTP request :frequency specifies how often to check :complete, :success, :failure associate with callbacks used depending on the outpcome of the reuqest
The Controller The fill_city_state method is added to the controller to handle the asynchronous request The render method is used to create the content of the response since it is simple text