Playing a Slideshow

Let’s see what happens when we try to play a slideshow. Browse to http://127.0.0.1:3000/slideshows, 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.

Playing a slideshow that still uses scaffolding

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

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
      @slide = @slideshow.slides[0]
    end

Every two seconds in this code (once we’ve updated the view code), the browser sends an Ajax request to get the next slide. You can’t use instance variables ...

Get Rails: Up and Running, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.