Rails : Generate local specific version of current page

If you are about to make your application locale specific then, you must come across with a problem of how you can get locale specific version of the currently hit page; so that your visitor can switch to different language versions of the same page.

There is a helper method called url_for. This method is used by every URLHelper in Rails internally [FYI].

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

For generating a new URL, the missing values may be filled in from the current request‘s parameters. Like, 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, in our case, you are only modifying/setting locale so, the other attributes are default to current request’s attributes.

But, problem with this approach is, I am getting the non-RESTful versions of URL. like

http://localhost:3000/signup?locale=en
# but I am expecting
http://localhost:3000/en/signup

Solution: I did not do anything; formerly the problem was there, but not the problem is gone. May be the application was needing some time to reload the updated code. So, its better to restart the application.

Advertisements

Its easy to determine URL in Rails

Rails has made so much easy to generate URL for RESTful resources. You don’t have to write the long route helper method; there exits a short hand method to be used; like

url_for [:edit, @parent_object, @resource_object]

Example:

When using book_article_path, you can just pass in instances of Book and Article instead of the numeric IDs:

<%= link_to 'Article details', book_article_path(@book, @article) %>

Moreover, you can use url_for with a set of objects, and Rails will automatically determine which route you want to generate:

<%= link_to 'Ad details', url_for([@book, @article]) %>

If you want any specific :action then try

<%= link_to 'Ad details', url_for([:edit, @book, @article]) %>

Some More

If you wanted to link to just a book:

<%= link_to 'Book details', @book %>

If you want to link to nested resource then

<%= link_to 'Article details', [@book, @article] %>

Note: the above technique will only work with link_to helper method.

 

 

Some useful links

http://guides.rubyonrails.org/routing.html