Sonntag, 9. März 2014

Simple RESTful Ruby on Rails routes.

Understanding the REST theory (read "REST in piece!"), Ruby on Rails routes are part of the praxis. Writing the routes to the resource and its RESTful API (actions) manually is definitely not an option.
First imagine the people_controller.rb once again:
class PeopleController < ApplicationController
  def index # GET

  def show # GET
  def new # GET
  def edit # GET
  def create # POST
  def update # PUT
  def destroy #DELETE
Adding the following line to your config/routes.rb:
resources :people
the command "rake routes" will show you the available routes to the actions:
people GET /people(.:format) people#index
POST /people(.:format) people#create
new_person GET /people/new(.:format) people#new
edit_person GET /people/:id/edit(.:format) people#edit
person GET /people/:id(.:format) people#show
PUT /people/:id(.:format) people#update
DELETE /people/:id(.:format) people#destroy
The entry into the routes.rb not only generates the available routes, it also generates some helpful helper methods.
Those helper methods can be used in the several view templates like:
<%= link_to "All people", people_path %>
<%= link_to "New person", new_person_path %>
<%= link_to "Show person", person_path(@person) %>
<%= link_to "Edit person", edit_person_path(@person) %>
<%= link_to "Delete person", person_path(@person), :method => :delete %>
<%= form_tag people_path do %>
  Create new person
<% end %>
<%= form_tag person_path(@person) do %>
  Update person
<% end %>
The responding HTML result:
All people
New person
Show person
Edit person
Delete person
Create new person
Update person
Please notice the link href and form action pathes. They are exactly the expected pathes to the REST actions, but without writing them manually. Though PUT and DELETE are injected by a Ruby on Rails trick.
Of course there is space for improvement. The same HTML result can be achieved using polymorphic routes behind the scenes:
<%= link_to "All people", :people %>
<%= link_to "New person", [:new, :person] %>
<%= link_to "Show person", @person %>
<%= link_to "Edit person", [:edit, @person] %>
<%= link_to "Delete person", @person, :method => :delete %>
<%= form_for do |f| %>
  Create new person
<% end %>
<%= form_for @person do |f| %>
  Update person
<% end %>
At this point the "" call is made only for illustrating that a new record is demanded.
Polymorphic routes are especially reasonable for views shared between various resources.

Supported by Ruby 1.9.3 and Ruby on Rails 3.2.3