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
  end

  def show # GET
  end
 
  def new # GET
  end
 
  def edit # GET
  end
 
  def create # POST
  end
 
  def update # PUT
  end
 
  def destroy #DELETE
  end
end
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 Person.new do |f| %>
  Create new person
<% end %>
<%= form_for @person do |f| %>
  Update person
<% end %>
At this point the "Person.new" call is made only for illustrating that a new record is demanded.
Polymorphic routes are especially reasonable for views shared between various resources.
Awesome!

Supported by Ruby 1.9.3 and Ruby on Rails 3.2.3