Search code examples
ruby-on-railsruby-on-rails-3routeslocale

rails routes with scope locale


I have add another language to my app. So, I am using the following routes for the static pages:

scope "(:locale)", locale: /en|br/ do
  get "static_pages/about"
  match '/about', to: 'static_pages#about'
  ...
end

it is working fine, resulting:

http://localhost:3000/en/about

However, each time I switch between languages it returns the full path instead of the match:

http://localhost:3000/en/static_pages/about

The way I am switching languages:

#links
<%= link_to (image_tag '/england.png'), url_for( locale: 'en' ) %>
<%= link_to (image_tag '/brazil.png'), url_for( locale: 'br' ) %>  

#application controller
before_filter :set_locale
def set_locale
  I18n.locale = params[:locale]
end

def default_url_options(options={})
  { locale: I18n.locale }
end

It is a problem because I am using the current path in my CSS file, so each time I switch language it is messing up the layout:

<%= link_to (t 'nav.about'), about_path, class: current_p(about_path) %> 

#helper
def current_p(path)
   "current" if current_page?(path)
end

I am trying to find a way to return the match route when switching languages. Any idea?


Solution

  • I have solved the problem combining match and get.
    So, instead of:

    scope "(:locale)", locale: /en|br/ do
      get "static_pages/about"
      match '/about', to: 'static_pages#about'
      ...
    end
    

    I have now:

    scope "(:locale)", locale: /en|br/ do
      match '/about', to: 'static_pages#about', via: 'get'
      ...
    end
    

    EDIT - Thanks to sevenseacat, an easier and shorter solution:

    scope "(:locale)", locale: /en|br/ do
      get '/about' => 'static_pages#about'
      ...
    end