Rails JavaScript Confirmation Helper



Ruby on Rails gives developers that extra bit of simplicity that is often overlooked. A perfect example is creating “delete” functionality within an application. There are generally a few ways this can be achieved. One of the simplest approaches I can think of is adding a JavaScript confirmation when the “delete” button is clicked. If the user accepts the confirmation then the entry is deleted, if not the page remains in its current state.

The link_to helper accepts a parameter called confirm that allows you to specify a confirmation message. If the confirmation is accepted, the user will be directed to the target action. A sample usage looks like:

link_to “Delete Me”, {:action => “delete”, :id => @item.id}, :confirm => “Are you sure you want to delete this item?”

This is fairly straightforward and the interesting thing is that this helper isn’t doing anything extraordinary. If you look at the rendered output you’ll see a basic inline JavaScript confirm implementation. It will look something like:

a xhref=”/delete/1″ onclick=”return confirm(’Are you sure…’);”>Delete Me /a

Nothing too complicated here, but I wanted to point out that Rails abstracts you from having to worry about all the nuances of writing inline JavaScript. One simple parameter gives you quit a bang for the buck.



One Response to “Rails JavaScript Confirmation Helper”

  1. Nick Ciske says:

    You generally want to avoid using a link to delete things… or people using web accelerators can find themselves inadvertently deleting everything they touch.

    The current recommended practive is to use a form submit instead, or block web accelerators from pre-fetching within your app (see link below)

    Google Web Accelerator: Hey, not so fast - an alert for web app designers

Leave a Reply