Jamie Gaskins

Ruby/Rails developer, coffee addict

Get Rid of ‘new’ and ‘edit’

Published Jul 11, 2012

In Rails, as well as several other "RESTful" web frameworks in various languages, provide 7 combinarions of URLs and HTTP verbs for accessing resources inside the app. In Rails, they are:

  • GET resources
  • POST resources
  • GET resources/:id
  • PUT resources/:id or PATCH resources/:id
  • DELETE resources/:id
  • GET resources/new
  • GET resources/:id/edit

The first two deal with collections of resources. GET retrieves the collection and POST adds to it. The next three deal with retrieving, modifying and removing an individual resource. The last two serve HTML forms for the user to generate or modify a resource.

Let me repeat that: the last two serve HTML forms. They do not actually interact with the resource at all. We put an HTML concern at the HTTP level.

My problem isn't necessarily that this happens at all. Surely, there are some things that make sense to have a page dedicated to them. But why do we do this by default? The default for Rails is to generate the new and edit form pages. But they're not really interacting with the resource. They're not "views". They're pages.

Let's take it out of the browser for a minute and into the realm of the native app. If you were going to create a new item for a list, even if this list were stored on remote hardware, would you ask that remote machine how to let the user enter the information for that? Hell no! You'd display a form you already had prepared. If you wanted to edit an item, would you ask the server for the item's details? Why would you do that? If you can see an item to tell the application to edit it, you already have its information. The only reason you'd open a connection to the server at all would be to ensure you had the most up-to-date version of that resource.

We can do the same thing in the browser. In the simplest case, we can provide the "new" HTML form inside the index view and the "edit" form inside the show view. With web clients getting thicker by the day like the dude from Super-Size Me, we don't even have to render separate "new" and "edit" forms. Render the same form for both, but pull the data from the show view into the form. Sure, Rails makes it so we don't even have to care about populating the form, but this is an example.

To be clear, I'm not ranting. The fact that we add two additional pages to each resource by default does bother me, but only about as much as, say, the effects of continental drift on the field of cartography. It's more the fact that we're leaning on the wrong thing for no other reason than "that's the way we've always done it" and I think we can come up with better ways to do it.