RESTful Routes

Now that you have a working scaffold for photos, we can move on to slides. In this section, we’ll create another default scaffold, but we’ll concentrate on the controllers, and the routes that Rails will use to access each resource. As you recall, a route tells Rails how to interpret an incoming URL. Given a route and a URL, Rails can determine:

  • The parameters that Rails will pass to the controller via the params hash

  • The controller Rails will access (stored in params[:controller])

  • The action that Rails will invoke (stored in params[:action])

Let’s see REST and routes in action. First, generate the scaffolding for a slide:

$ script/generate scaffold slide position:integer photo_id:integer slideshow_id:integer
...
      create  app/views/slides
      create  app/views/slides/index.html.erb
      create  app/views/slides/show.html.erb
      create  app/views/slides/new.html.erb
      create  app/views/slides/edit.html.erb
      create  app/views/layouts/slides.html.erb
...
      create  app/controllers/slides_controller.rb
      create  test/functional/slides_controller_test.rb
...
       route  map.resources :slides
...

As you learned last time, Rails creates a bunch of files for you. This time, we’ll focus on the controllers, views, and the route. As before, a little test data will make it easier to test the application. This time, we’re going to take advantage of templating features. Ruby’s ERb interprets the fixture files just like it does views. Edit test/fixtures/slides.yml to look like this:

<% 1.upto(9) do |i| %> slide_<%= i %>: ...

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.