OR “Beware of pick pockets and loose link_to’s”
I hope most rails dev’s out there take advantage of RESTful routes and the url-generating helpers so readily available these days and actually enjoy them. But for some of you who are lucky enough to inherit a legacy app (you know, 1 year olds) or for whatever reason encounter loosely defined link_to’s [exemplified below], you can easily update the code to avoid some gotchas.
This is what I consider a loosely defined link_to:
link_to 'Destroy', some_record, :confirm => 'Are you sure?', :method => :delete
It lacks parentheses, option grouping, and most importantly, expects the helpers to generate a specific kind of link (in this case a destroy action) from just the record itself. Now, rails is pretty smart these days and will probably generate the correct link without a hiccup if your app isn’t employing a custom RAILS_RELATIVE_URL_ROOT, or setting skip_relative_url_root => false.
Well, my latest app is. And this is how that loosely defined link_to renders:
ArgumentError in Controller#action
wrong number of arguments (0 for 1)
The stack trace will provide evidence that some thing’s a mess in url_for related to the default_url_options, defined in application.rb (or elsewhere). Rails’ helpers cannot correctly produce a url due to lazy linking.
So, make your code more readable and keep the helpers happy and define your link_to’s like this:
link_to ( 'Destroy', record_path(some_record), :confirm => 'Are you sure?', :method => :delete )
Refresh that error page and voila! Happy links again! Stricter coders may even group the options with curlies, and that doesn’t hurt either.