Question

I want my routes to have the format /locale/route instead of /route?locale=en, etc.

I have the following in application_controller.rb

before_filter :set_locale

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

  private
    def set_locale
      I18n.locale = (params[:locale] if params[:locale].present?) || cookies[:locale] || 'en'
      cookies[:locale] = I18n.locale if cookies[:locale] != I18n.locale.to_s
    end

I have this in routes.rb

scope "/:locale" do
  all my routes except for the root
end

I have the following code for the root path outside of the scope statement. When I had these in the scope statement it set the locale to 404 and did not find a locale file for 404.

match '/:locale' => 'landing#index'
root            to: 'landing#index'

Here is the code in my heading view where people can change the language:

<p class="locale-line"><span class="english-link"><%= link_to_unless_current "#{t :english}", locale: "en" %></span><%= link_to_unless_current "#{t :french}", locale: "fr" %></p>

Here is the code for a link using an image that returns to the root path:

<%= link_to image_tag("menu-home.jpg", alt: "My Home Page"), root_path %>

<%= link_to image_tag("menu-home.jpg", alt: "My Home Page"), root_url %>

I am able to successfully get the routes within the scope statement to display the routes as desired. When a person initially displays the website and they click either language link at the top of the page the root path displays with /locale. However my root path does not work like I want with the image tag. Both examples display the root path with /?locale=en or /?locale=fr.

I have checked guides.rubyonrails.org and edgeguides.rubyonrails.org but did not find any examples of how to code the link_to statement for the root path where it will display the locale with format /locale.

Any help would be appreciated.

Was it helpful?

Solution

Try this in routes.rb

match '/:locale' => 'landing#index', :as => 'locale_root'

And then link to it like this:

<%= link_to image_tag("menu-home.jpg"), locale_root_path %>

Or you may need to do

<%= link_to image_tag("menu-home.jpg"), locale_root_path(:locale => I18n.locale) %>

(I removed the alt param just to save space so that everything fits in the page.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top