Javascript for Rails
This article was prompted by the problems caused when using a restful design and deleting things with link_to
There are several issues to consider here
- obtrusive javascript
- supporting browsers where javascript is disabled
- restful design and current browser limitations
restful design and current browser limitations
Restful design stipulates that to delete a resource you should call its url using the delete
method on it. So with an item foo
you would use the same url to delete and show foo
- www.example.com/foo with GET to show
- www.example.com/foo with DELETE to delete
However current browsers only support the GET and POST verbs, so we have to get around this. What Rails does is overload POST passing the method (PUSH, DELETE, HEAD?). This means a form has to be created for each delete link. Rails uses javascript to create this form on the fly (and the very convenient confirmation dialog. This approach allows us to use the correct REST url to delete things.
supporting browsers where javascript is disabled
When javascript is disabled it becomes harder to delete things. If we try and use a link to delete we will instead send a GET and show foo. Rails does this because without javascript we cannot rely on the additional safety of a browser side confirmation. So Rails says we should not use a link for deleting but instead use a button (use method button_to
). However buttons are clunky so people expect to be able to work around this limitation. There are a couple of solutions to this problem
- use a button rather than a link, and lose the ability to confirm that action
- insist on javascript so we can use pretty links to delete and have our confirm
- create another url for deleting things which will show a confirmation form when javascript is disabled and then post the DELETE (this breaks the RESTFUL design a little)
- wait for browser to support DELETE
obtrusive javascript
Another problem highlighted by this issue is the yukky javascript that the Rails helpers insert directly into our HTML. If we have a table of items that can be deleted we end up with 5 lines of convoluted javascript for each item. So we have our beautiful semantic html polluted by reams of ‘obtrusive javascript’. I’ll talk about this issue further in a separate post