HTTP PATCH Verb [Rails 4 Countdown to 2013]

Posted on

This post is part of a series of 31 Rails 4 articles being released each day in December 2012.

When updating a resource in Rails, most often than not it is a partial update. The PUT HTTP verb is meant to be used for the creation or replacement of a resource at a given URL. Rarely, if ever, do you replace an entire resource when performing an update.

RFC 5789 explained the difference between PUT and PATCH in the following except:

"In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version."

Over two years ago, David Lee submitted a pull request which mapped the PATCH HTTP verb to update controller actions to follow proper REST semantics. This change is finally making its way into Rails as of version 4.0.

The best example of why PATCH should be used over PUT was given by Xavier Noria on the official Rails blog. In that post, Xavier used the created_at and updated_at timestamps as prime examples of fields not being set by end-users when updating an Active Record model.

Rails 4 Changes

The switch to the PATCH HTTP verb will not have any affect in your applications during the upgrade process. If you are explicitly setting the PUT verb, such as in a form, update it to use :patch. For those who are interested, here are the main areas of change:

  • In the router, PATCH requests are routed to the update action. This change is backwards compatible, so requests to PUT will work the same way.
  • Forms will set the hidden field _method to :patch on edits.

Further Reading

002

This post is by Kevin Faustino. Kevin is the Chief Craftsman of Remarkable Labs and also the founder of the Toronto Ruby Brigade.


Comments

comments powered by Disqus