Examining a RESTful Controller

Rails scaffolding is a very conscious implementation of REST, an example generally worth emulating and extending. Even in cases where browser limitations keep REST from working as simply as it should, Rails fills the gaps so that you can focus on building your application, not on corner cases. The simple one-field application shown earlier is enough to demonstrate the principles that Rails has used to generate the scaffolding.

Opening the app/controllers/people_controller.rb file reveals Example 5-1. It defines seven methods, each prefaced with a sample of the HTTP request that should call it. This chapter will explore each method individually, but take a moment to explore the whole thing and get a feel for what’s going on, and how these methods are similar and different.

Example 5-1. A RESTful controller created as part of Rails scaffolding

class PeopleController < ApplicationController # GET /people # GET /people.xml def index @people = Person.find(:all) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @people } end end # GET /people/1 # GET /people/1.xml def show @person = Person.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @person } end end # GET /people/new # GET /people/new.xml def new @person = Person.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @person } end end # GET /people/1/edit def edit @person = Person.find(params[:id]) ...

Get Learning Rails: Live 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.