Future on Rails

Using Rails

Posts Tagged ‘rails view design

Organizing Views for Resources

leave a comment »

When developing a Rails application, most of the objects we deal with are “resources” (well, that’s if we think RESTful, of course ;)). I noticed I use a common theme to organize the view part of those resources.

The straight forward way would be to have a view for most every REST action: index, new, edit and show. What I noticed is, that new and edit are very similar: both present a form to edit the resource. So the first thing I usually do is to create a partial called _form.html.erb to refactor the common parts of new and edit into. You could even go further: in many modern applications, the user should be able to perform “in place editing” of resources. This means that the show view basically represents show, edit and new all in one. Depending on the case at hand you could either eliminate all those views and simply use “show” for all actions or you could keep them and extract the common code into a partial (like the _form.html.erb mentioned above).

Another commonality among resources is that they’re views of a single resource or a list of resources. The single resource is usually presented in the new, edit and show views, the list is usually presented in the index view. But in a real world application you might want to display resources or lists of resources in different places on your site. You might e.g. have a kind of dashboard where the user has an overview over some of her resources. To facilitate this code reuse, I usually create two view partials for each resource: a _widget.html.erb displaying a single resource, and a _list.html.erb displaying a list of all resources (maybe filtered/limited by some (search) criteria). These two partials can then be used in every place where those resources need to be displayed. In very simple cases, the _list.html.erb might not be necessary, because you could use the widget partial with a collection. 

I hope, my organization of resource views gives you useful ideas how to design your code. I’m always eager to learn and would appreciate any thoughts on this topic!

Written by Matthias Orgler

April 29, 2009 at 1:17 pm

Posted in code design, refactoring

Tagged with