Rails link to current page and passing parameters to it

Took me a while to find this but here is my solution:

link_to 'English', url_for( :locale => 'en' )
link_to 'Deutch', url_for( :locale => 'de' ) 

From the docs here: http://api.rubyonrails.org/classes/ActionController/Base.html#M000649

When generating a new URL, missing
values may be filled in from the
current request‘s parameters. For
example, url_for :action =>
‘some_action‘ will retain the current
controller, as expected. This behavior
extends to other parameters, including
:controller, :id, and any other
parameters that are placed into a
Route‘s path.

So using url_for will default to the current request’s parameters, just change the one’s you want in your code. In this case all I changed was :locale, so everything else stays the same.

Note this also works for “hidden” :parameters. So if you have:

map.my_map ':locale/my_map', :controller => 'home', :action => 'my_map'

using the above url_for in the page /en/my_map will not have ‘home’ in the url (ie /en/home/my_map). Bonus.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)