:use_route param for Rails URL helper

Posted by Peter Wagenet Sat, 25 Apr 2009 18:25:00 GMT

Imagine the following case. You have two landing pages, one generic one, and an account specific one. The urls are as follows:

map.landing 'landing', :controller => 'landing', :action => 'index'
map.account_landing 'accounts/:account_id/landing', :controller => 'landing', :action => 'index'

Now imagine you want a path to the landing page, using the most specific route possible. If you have an account_id, use it, if not, skip it.

You could do:

url_for(:controller => 'landing', :action => 'index', :account_id => current_account)

If current_account is set you’ll get “/accounts/:account_id/landing” if not, you’ll get “/landing”. However, that just looks ugly.

Enter :use_route => nil.

landing_path(:account_id => nil)                    # => '/landing'
landing_path(:account_id => 1)                      # => '/landing?account_id=1'
landing_path(:account_id => nil, :use_route => nil) # => '/landing'
landing_path(:account_id => 1, :use_route => nil)   # => '/accounts/1/landing'

Setting :use_route to nil, is equivalent to the earlier #url_for example.

Another use for :use_route is to force a route helper when using :url_for.

For instance, you can do:

url_for(:controller => 'landing', :action => 'index', :account_id => 1, :use_route => :landing)
# => '/landing?account_id=1'

Though it’s not likely you would want that specific outcome, if you need to force #url_for to use a specific route form, it can be done.

This is likely to be most of use when working with a plugin, such as will_paginate, that calls #url_for internally.

Thanks to matbrown for the second tip.

Comments

Leave a comment

Comments