Create a restful Resource
Problem
You 've heard all the buzz about creating restful this and that. There's
Little doubt that rails 2.0 heavily favors the rest into tural style1
And that it will continue to do so.
You're feeling a little out of the loop, and what you 've got so far is
A tad too academic. As a practical matter, you 'd like to create a web-
Accessible API for one of your models and write a client program
Administer that model remotely. What can resources do for you?
Solution
Let's forget about rest for a moment and try to solve a problem. Sup-
Pose we organize events and we want a Web-based interface for creating,
Reading, updating, and deleting events (affectionately known as crud ).
The first part of the solution comes in a single command, but what it
Does can be confusing. The scaffold generator chilns out all the crud
Support code for administering events in a restful way.2 we'll put up
Event scaffolding in one fell swoop:
$ Script/generate scaffold event name: String Description: Text success
Capacity: integer price: decimal starts_at: datetime
That single command generates a bunch of code: a model, a controller
With no fewer than seven actions, view template files for actions that
Need them, tests, and even a migration file with the database Columns
We listed on the command line.
Next, we just need to create the database and apply the Migration:
$ Rake DB: Create
$ Rake DB: migrate
That's all there is to it! Fire up the application, and, lo and behold, we
Now have a full HTML interface to CRUD (the verb form) events.
Before we move on to the second part of the solution, let's dive a bit
Deeper to see what just happened. In some ways, it's just like the old
Rails scaffolding, but there's a significant twist. You may have noticed
That the following line was added to our config/routes. RB file:
Map. Resources: Events
That line is the key ingredient to our restful application. It dynam-
Ically creates a set of named restful routes for accessing our events
(Called resources) via URLs. The routes map to the seven actions in our
Controller: Index, show, new, create, edit, update, and destroy.
The best way to see what's going on behind the scenes is to print out
All the defined routes by typing this:
$ Rake routes
Let's look at a few just to get a taste of how this works (you'll see more in
Your output). First, we have routes for dealing with the events collection:
Events get/events {: controller => "Events",: Action => "Index "}
Post/events {: controller => "Events",: Action => "CREATE "}
The leftmost column gives the name of the route (events), followed
The matching HTTP verb and URL path, and then the action/Controller
Pair that the route ends up invoking. So, to list all our events-
Index action-we wocould issue an http get request to the URI/events.
Then, inside our application, we use the events_url route helper to gen-
Erate the full URL for listing events. (Alternatively, you can use
Events_path method to just get the path part of the URL, often referred
To as the URI .)
Notice that the same incoming URL path is mapped to our create action.
The only difference is the HTTP verb that's used: get is a read-only
Operation that lists the events, and post is a write operation that re-
Ates a new event.
We also have restful routes for dealing with a specific member of
Events collection:
Event get/events/: Id {: controller => "Events",: Action => "show "}
Put/events/: Id {: controller => "Events",: Action => "Update "}
In these cases, the name of the route is singular (event) because it's
Dealing with one particle event. Again, the URL path is the same
Both actions. The HTTP verb is used to disambiguate whether we want
To read or update a single event by its primary key (The: Id route param-
ETER). Inside our application, we use the event_url (@ event) Route helper,
For example, to generate a URL to show our event. Passing @ event
The route helper will automatically fill in the: Id route parameter
The ID of the event.
So, in a nutshell, the map. Resources line generates restful routes
Our application based on both the incoming URL path and an HTTP
Verb. Now, browsers generally issue get and post requests, leaving
The other HTTP verbs to the academics. So, how do we tell our appli-
Cation that we want to update an existing event (the put verb) or
Delete an event (the delete verb )? Well, that involves a few more new
Conventions.
If we have an @ event model object (and it's declared to be a resource ),
Then in our new.html. ERB and edit.html. ERB forms, we can simply use this:
Download rest/APP/views/events/new.html. ERB
<% Form_for @ event do | f |-%>
The form_for will generate the appropriate form tag depending on
State of the @ event object. If it's a new record that hasn't yet been saved,
Rails knows that it needs to be created. So, the form_for generates a form
Tag that looks like this:
<Form action = "/events" method = "Post">
This form will post to our create action because, according to the rest-
Ful routing conventions, the HTTP verb and URL path map to that
Action.
However, if the event is an existing record that has previusly been
Saved, then rails knows we're re trying to update it. In this case, the form
Shocould post to the update action. To do that, the form_for method slaps
In a hidden field to simulate a put operation. This in turn triggers
The proper restful route when rails intercepts the request. It looks
Something like this in the generated form:
<Form action = "/events/1" method = "Post">
<Input name = "_ method" type = "hidden" value = "put"/>
OK, so at the end of all this, we're re still administering events in
Browser, just with special URLs. The immediate upshot is we can turn
Any of our models into resources-events, registrations, users, and so
On-and then administer them through a consistent URL scheme. It's
Just one more example of rails conventions removing guesswork.
Now let's move on to the second part of the solution. Let's say we 'd like
To write a client program to administer events remotely. We'll have our
Client program speak XML back and forth with our rails Application
(Imagine what that must sound like !). To do that, let's turn our atten-
Tion to the scaffold-generated index action in our eventscontroller. It has
All the familiar stuff, plus a respond_to block:
Download rest/APP/controllers/events_controller.rb
Def Index
@ Events = event. Find (: All)
Respond_to do | format |
Format.html # index.html. ERB
Format. xml {render: XML =>@ events}
End
End
The action starts by setting up a collection of events. The respond_to
Block determines how those events are rendered based on which-
Mat the client requests. By default, browsers prefer the HTML format.
In that case, the index action renders the index.html. ERB template to gen-
Erate an HTML response.
However, the index action also responds to requests for events in
XML format. To get the collection of events as XML, we just need our
Client program to issue a GET request with. xml tacked to the end of
URL, like this:
Http: // localhost: 3000/events. xml
Here's where things get interesting. We already have a consistent way
To administer our events using the restful URL conventions. And we
Already have a way to Vary how the events are represented using
Respond_to block in actions.
Therefore, we already have a web-accessible API to our event resources.
All we need to do is write a client program to administer our events
Remotely. Active resource makes that really easy.
First, we write a stand-alone Ruby program: the active resource client.
(I typically put these in a Services Directory, But they cocould live any-
Where.) It doesn' t need to load rails per se, but we do need to require
The activeresource GEM:
Download rest/services/event_client.rb
Require 'rubygems'
Require 'activersource'
Then we create an event proxy class that points to the server where
Event resources live:
Download rest/services/event_client.rb
Class event <activeresource: Base
Self. Site = "http: // localhost: 3000"
End
Active resource now knows how to build URLs for accessing our event
Resources, and it'll push XML over HTTP until the cows come home.
Indeed, here's where having an application that responds to XML really
Shines. All the standard crud-level operations are available, as if our
Proxy class were a real active record model.
Next, we'll find all the events and print their names:
Download rest/services/event_client.rb
Events = event. Find (: All)
Puts events. Map (&: name)
Then we'll find a specific event and update its attributes:
Download rest/services/event_client.rb
E = event. Find (1)
E. Price = 20.00
E. Save
Finally, we'll create and delete an event:
Download rest/services/event_client.rb
E = event. Create (: Name => "shortest event EVAR! ",
: Starts_at => 1. Second. Ago,
: Capacity => 25,
: Price => 10.00)
E. Destroy
Before we run the client, we'll configure a logger to see what happened
Behind the scenes by adding this line before the event class definition:
Download rest/services/event_client.rb
Activeresource: Base. Logger = logger. New ("# {file. dirname (_ file _)}/events. log ")
Then, to run the client, we just use this:
$ Ruby event_client.rb
Here's the output in the events. log file, which can be quite handy
Debugging an ornery client:
Get http: // localhost: 3000/events. xml
--> 200 OK (<? XML version = "1.0" encoding = "UTF-8"?> ...
Get http: // localhost: 3000/events/1.xml
--> 200 OK (<? XML version = "1.0" encoding = "UTF-8"?> ...
Put http: // localhost: 3000/events/1.xml
--> 200 OK (B 0.11 s)
Post http: // localhost: 3000/events. xml
--> 201 created (<? XML version = "1.0" encoding = "UTF-8"?> ...
Delete http: // localhost: 3000/events/12.xml
--> 200 OK (B 0.11 s)
Now we have a full API for creating, reading, updating, and deleting
Events via the browser or a remote client program. And we have conven-
Tions: a consistent set of URLs that map to a consistent set of actions.
This generally makes deciding where things go a lot easier. In particle,
We no longer have controllers that are dumping grounds for spurious
Actions.
Discussion
It is important to note here that rest (Map. Resources in particle)
And respond_to blocks are orthogonal. You can use respond_to
Resources, and vice versa.
Although active resource ships with rails and uses some of its support
Classes, it's not necessarily rails-specific. You can use it to reach out
To any server supporting the restful conventions of rails.
Also see
The map. Resources method generates routes only for the seven crud
Actions. This begs the question, how do I call actions outside of this
Set? Recipe 2, add your own restful actions, on the following page
Shows how to customize the routes for application-specific concerns.