Restful architecture does not mean one to one mapping

Neeraj Singh

Neeraj Singh

February 17, 2009

Rails makes it easy to adapt Restful architecture. All you have to do is following.

1map.resources :pictures

I started putting all pictures related activities in pictures_controller.rb . In the beginning it was simple.

Slowly the application evolved. The application started handling two different types of pictures. There would be pictures for events and then there would be pictures of users using the system.

One can add comments to the event pictures but one can't add comment to user pictures. Slowly the requirement for event pictures grew vastly different from user pictures.

Sounds familiar. Right. Initially controller takes on a few responsibilities but slowly the controller starts taking a lot more responsibilities and then controller becomes huge.

The pictures controller was really huge and was fast becoming a mess and specially writing test was getting very difficult.

Time had come to create two different controllers: one for event pictures and one for user pictures.

But wait. Lots of people would say that if we want to be restful then there has to be one to one mapping between the model and the controller. Not true.

Model != resource

Being restful does not mean that there has be a one to one mapping between the model and the controller.

I am going to create a new controller called user_pictures_controller.rb which will take on all the functionality related to users dealing with picture. And this is going to be restful.

1map.resources :user_pictures

Above I have defined a resource called user_pictures. To keep it simple this controller would do only three things.

  • display all the pictures of the user ( index )
  • allow user to upload pictures ( create )
  • allow user to delete a picture ( destroy )

That's the general idea. In my application I have only three actions.

However in the interest of general discussion I am going to show all the seven methods here. Also for simplicity create in this case means adding a record (I am not showing multipart upload).

Controller

Here is the code for controller.

1
2# user_pictures_controller.rb
3
4class UserPicturesController < ApplicationController
5
6  def index
7    @pictures = Picture.all
8  end
9
10  def new
11    render
12  end
13
14  def create
15    @picture = Picture.new(params[:picture])
16    if @picture.save
17      flash[:notice] = 'Picture was successfully created.'
18      redirect_to user_picture_path(:id => @picture.id)
19    else
20      render :action => "new"
21    end
22  end
23
24  def show
25    @picture = Picture.find(params[:id])
26  end
27
28  def edit
29    @picture = Picture.find(params[:id])
30  end
31
32  def update
33    @picture = Picture.find(params[:id])
34    if @picture.update_attributes(params[:picture])
35      flash[:notice] = 'Picture was successfully updated.'
36      redirect_to user_picture_path(:id => @picture.id)
37    else
38      render :action => "edit"
39    end
40  end
41
42  def destroy
43    @picture = Picture.find(params[:id])
44    @picture.destroy
45
46    redirect_to user_pictures_path
47  end
48
49end

View

1# index.html.erb
2<h1>Listing pictures</h1>
3
4<table>
5  <tr>
6    <th>Name</th>
7    <th>Quality</th>
8  </tr>
9
10<% for picture in @pictures %>
11  <tr>
12    <td><%=h picture.name %></td>
13    <td><%=h picture.quality %></td>
14    <td><%= link_to 'Show', user_picture_path(picture) %></td>
15    <td><%= link_to 'Edit', edit_user_picture_path(picture) %></td>
16    <td>  <%= link_to 'Destroy',  user_picture_path(picture),
17                                :confirm => 'Are you sure?',
18                                :method => :delete %>
19
20    </td>
21  </tr>
22<% end %>
23</table>
24
25
26<%= link_to 'New picture', new_user_picture_path %>
1# edit.html.erb
2<h1>Editing picture</h1>
3
4<% form_for(:picture,
5            :url => user_picture_path(@picture),
6            :html => {:method => :put}) do |f| %>
7  <%= f.error_messages %>
8
9  <p>
10    <%= f.label :name %><br />
11    <%= f.text_field :name %>
12  </p>
13  <p>
14    <%= f.label :quality %><br />
15    <%= f.text_field :quality %>
16  </p>
17  <p>
18    <%= f.submit "Update" %>
19  </p>
20<% end %>
21
22<%= link_to 'Show', user_picture_path(@picture) %> |
23<%= link_to 'All', user_pictures_path %>
1# new.html.erb
2<h1>New picture</h1>
3
4<% form_for(:picture, :url => user_pictures_path, :html => {:method => :post}) do |f| %>
5  <%= f.error_messages %>
6
7  <p>
8    <%= f.label :name %><br />
9    <%= f.text_field :name %>
10  </p>
11  <p>
12    <%= f.label :quality %><br />
13    <%= f.text_field :quality %>
14  </p>
15  <p>
16    <%= f.submit "Create" %>
17  </p>
18<% end %>
19
20<%= link_to 'All', user_pictures_path %>
21
1# show.html.erb
2<p>
3  <b>Name:</b>
4  <%=h @picture.name %>
5</p>
6
7<p>
8  <b>Quality:</b>
9  <%=h @picture.quality %>
10</p>
11
12<%= link_to 'Edit', edit_user_picture_path(:id => @picture) %> |
13<%= link_to 'All', user_pictures_path %>

Another use case

Let's talk about another example. Let's say that we have a model called Project and besides the regular functionality of creating, deleting, updating and listing projects, one needs two more actions called enable and disable project.

Well the projects controller can easily handle two more actions called "enable" and "disable". However it is a good idea to create another controller called project_status_controller . This controller should have only two actions - create and destroy. destroy in this case would mean disabling the project and create would mean enabling the project.

I know it looks counter intuitive. Actions 'enable' and 'disable' seem simpler than "create" and "destroy". I agree in the beginning adding more actions to pictures controller looks easy. However if we go down that path then it is a slippery slope and we do not know when to stop.

Compare that with the RESTful design of having only seven action : index, show, new, edit, create, update, destroy. This limits what a controller can do and that's a good thing. This ensures that a controller does not take up too many responsibilities.

Creating another controller allows all the business logic which is not related to one of those seven actions to be somewhere else.

One last example

Now that we have the ability to "enable" and "disable" pictures how about showing "only active", "only inactive" and "all" pictures.

In order to accomplish it once again we can add more actions to the pictures controller.

However it is much better to have two new controllers.

1class Pictures::ActiveController < ApplicationController
2end
3
4class Pictures::InactiveController < ApplicationController
5end

Some of you must be thinking what's the point of having a controller for the sake of having only one action. Well the point is having code that can be changed easily and with confidence.

Conclusion

In this blog I tried to show that it is not necessary to have one to one mapping between model and controllers to be restful. It is always a good idea to create a separate controller when the existing controller is burdened with too much work.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.