SmartLogic Logo (443) 451-3001

The SmartLogic Blog

SmartLogic is a web and mobile product development studio based in Baltimore. Contact us for help building your product or visit our website to learn more about what we do.

Loosely defined link_to may cause problems when overriding url_helper

August 26th, 2008 by

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.

map.resources and custom nested routes

June 5th, 2008 by

I encountered an error in rails trying to create a nested route in rails 2.x

map.import_time_cards 'users/:user_id/time_cards/import',
:controller => 'time_cards',
:action => 'import'

Wasn’t setting up a route for users because this route was being setup automatically and overwritten by:

map.resources :users,
:has_many => [:notes, :addresses, :expenses, :time_cards] ,
:collection => [:login, :logout, :disable, :enable]

So after digging around on the rails api I discovered that map.resources takes a block so my solution to this problem was :

map.resources(:users,
:has_many => [:notes, :addresses, :expenses] ,
:collection => [:login, :logout, :disable, :enable]) do |user|
user.resources :time_cards, :collection => [:import]
end

By using a block this tells rails to include route to ‘users/1/time_cards/import’ instead of appending import as the id for the show route.

  • You are currently browsing the archives for the Routing category.