Home arrow Ruby-on-Rails arrow Page 2 - Introduction to Ruby on Rails with Ajax
RUBY-ON-RAILS

Introduction to Ruby on Rails with Ajax


In this first article in a two-part series, you will learn how Ruby on Rails implements Ajax. We will use the specific example of a slideshow to demonstrate our points. This article is excerpted from chapter six of the book Ruby on Rails: Up and Running, written by Bruce A. Tate and Curt Hibbs (O'Reilly, 2006; ISBN: 0596101325). Copyright © 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Author Info:
By: O'Reilly Media
Rating: 4 stars4 stars4 stars4 stars4 stars / 3
July 26, 2007
TABLE OF CONTENTS:
  1. · Introduction to Ruby on Rails with Ajax
  2. · Playing a Slideshow
  3. · Using Drag-and-Drop to Reorder Slides
  4. · Using Drag-and-Drop to Reorder Slides continued

print this article
SEARCH DEVARTICLES

TOOLS YOU CAN USE

advertisement
Introduction to Ruby on Rails with Ajax - Playing a Slideshow
(Page 2 of 4 )

Let's see what happens when we try to play a slideshow. Browse to http://127.0.0.1: 3000/slideshows/list, and click the Play link for our only slideshow. As you can see in Figure 6-1, this URL invokes the show action on the slideshow controller, but the action is still using the scaffold code.

We need to change this page to actually "play" the slideshow by sequentially displaying the pictures contained in the slideshow. To do this, we will initially display the first picture in the slideshow; then, once every two seconds, we'll make an Ajax call to get and display the next picture.

The controller sets up all the slides in a slideshow for playback. You need to start @slideshow with the current slideshow set to play. You also need to put the current slide (initially, 0) and the whole slideshow into a holding area called the session, so you won't have to read from the database each time you play a new slide. Edit the slideshows controller (app/controllers/slideshows_controller.rb), and modify the show method to look like this:

  def show
   
@slideshow = Slideshow.find(params[:id])
    session[:slideshow] = @slideshow
   
session[:slide_index] = 0


Figure 6-1.  Playing a slideshow that still uses scaffolding

    @slide = @slideshow.slides[0]
  end

Every two seconds in this code, the browser sends an Ajax request to get the next slide. You can't use instance variables to keep track of where you are in the slideshow because instance variables exist only until you finish processing the current request. Use the Rails-provided session object instead, which is persistent across requests. Let's look at this code in a little more detail.

session[:slideshow] = @slideshow stores a reference to the current slideshow in the session hash at the key :slideshow. We do the same thing with the index of the current slide that is being played. We initially set the slide_index to zero to point to the first slide, and our Ajax request increments the index by one as it displays each slide. We can retrieve these values from the session hash during the Ajax requests for the next slide.

Now, edit the view template (app/views/slideshows/show.rhtml) to look like this:

  <p><i><%= @slideshow.name %></i></p>

  <div id="slides">
    <%= render :partial => "show_slide" %>
 
  </div> 

  <%= periodically_call_remote :update    => 'slides',
                               
:url       => { :action => :show_slide },
                              
:frequency => 2.0 %>

This RHTML template contains three things: a title line, the div that displays the current slide, and a magic Ajax incantation that we will now pick apart.

The periodically_call_remote Rails helper function creates JavaScript that periodically sends a request to the server and uses the HTML fragment that is returned to replace the content of the update target. In this case, the update target is an HTML element with an ID of 'slides', which is a <div> tag. The returned HTML fragment replaces the contents of this <div> tag. The URL that makes the request is constructed to ensure that it will be routed to the show_slide method of the current controller (the slideshows controller). Finally, the frequency parameter makes the call once every two seconds. All Ajax help functions take their parameters in key/value pairs, so you can list the parameters in any order.

We need to display each slide as it comes back to the client; Rails uses a partial HTML template to do this work. To create the partial view template, place the following contents in a new file called app/views/slideshows/_show_slide.rhtml:

  <%= image_tag "photos/#{@slide.photo.filename}" %>
  <p><%= @slide.photo.filename %></p>

And its controller method in app/controllers/slideshows_controller.rb:

  def show_slide
   
@slideshow = session[:slideshow]
   
session[:slide_index] += 1
   
@slide = @slideshow.slides[session[:slide_index]]
   
if @slide == nil
      
session[:slide_index] = 0
      
@slide = @slideshow.slides[0]
   
end
   
render :partial => "show_slide"
  end

This method retrieves the slideshow information from the session, moves to the next slide (or back to the beginning if at the end), and then explicitly renders the partial view template show_slide. You need to render a partial view or render with the option :render_layout => false . Otherwise, Rails tries to render a full template, including layout. As our page already has a layout, simply render a partial template, consisting of an image tag for the slide, and its name.

Finally, you need to update your standard layout template to include script tags for the Prototype JavaScript library because the client-side JavaScript code that Rails creates for you uses them, so in app/views/layouts/standard.rhtml, insert this line immediately after the title tags:

  <%= javascript_include_tag 'prototype', 'effects', 'dragdrop' %>

This line includes three JavaScript files that are shipped with Rails: prototype.js and two Script.aculos.us files, effects.js and dragdrop.js. We will use these last two shortly.

Now show a slideshow by loading slideshows/list and clicking Show, and you will see the actual pictures in the slideshow, changing every two seconds.


blog comments powered by Disqus
RUBY-ON-RAILS ARTICLES

- Adding Style with Action Pack
- Handling HTML in Templates with Action Pack
- Filters, Controllers and Helpers in Action P...
- Action Pack and Controller Filters
- Action Pack Categories and Events
- Logging Out, Events and Templates with Actio...
- Action Pack Sessions and Architecture
- More on Action Pack Partial Templates
- Action Pack Partial Templates
- Displaying Error Messages with the Action Pa...
- Action Pack Request Parameters
- Creating an Action Pack Registration Form
- Ruby on Rails Templates and Layouts
- Action Pack Controller Creation
- Writing an Action Pack Controller

Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 



© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 3 - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials