Unobtrusive RESTful links in Rails

In a recent project, I wanted a link that modifies a row in the database. The provided mockup wanted a link. “To follow the rules of RESTful architecture, anything modifying the database, should not be a GET request” I thought to myself. I realised that Rails provides me with both a link_to and a button_to helper but no hybrid that would be unobtrusive, so I knew I had to make one.

The snippet adds a link after the form, hides the form and make the link submit the form. I have made it non-conflicting to those who use other libraries and jQuery.

To install:

  • Use jRails or have the jQuery library included (Prototype not needed)
  • Add the snippet to your application.js
  • Create your button_to’s with the class :class => "form_to_link"

Thanks to Kyle Neath and Rein Henrichs with this.

6 Responses to “Unobtrusive RESTful links in Rails”


  1. 1 Will Green

    Why not use an HTML Button? That is, a tag, not . You can style it to look like a link, it behaves like a button (because it is one), and no JavaScript is required.

    See http://particletree.com/features/rediscovering-the-button-element/ for an example of styling anchors and buttons to look alike.

  2. 2 Jeff

    Just wondering, why wouldn’t link_to_remote work for this situation? Or maybe I’m missing something obvious…?

    Thanks!

  3. 3 Will Green

    Second sentence should read:

    That is, a button tag, not input type=”button”.

  4. 4 Zach Inglis

    Jeff: Link to remote is for an AJAX call. I do not want it to be AJAX. I just want it to look right.

    Will Green: The button is also handy but there is also a ton of trickery involved still.

  5. 5 Will Green

    CSS “trickery” vs JavaScript trickery. The button will still submit the form without JavaScript. The anchor will not. Thus, styling the button is the truly unobtrusive option.

  6. 6 Rein Henrichs

    Will is right about styling a button tag (although it isn’t perfect, it’s usually good enough).

    Even if that solution obsoletes this one for this specific use, I think this is a good example of how to evolve jQuery written in a procedural (but effective) way into modular (pluginized) code. The revision history of the final Gist is educational, including a few flubs by yours truly.

Leave a Reply