Rails link to current page and passing parameters to it

前端 未结 8 992

I am adding I18N to my rails application by passing the locale using url params. My urls are looking like http://example.com/en/users and http://example.com/ar/users (for th

8条回答
  •  心在旅途
    2020-12-13 00:15

    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.

提交回复
热议问题