Img source:

Globalize is one of the most famous gems that is used for translating dynamic content in Rails application. It is really easy to use, and brings a lot of conveniences immediately after you add it in your application. I recently had to do a more complex query using the table added by Globalize generator, and I could not find that much information about ways of doing joins for this newly added table with the one that it corresponds and that translates its attributes. In this article, you can see a short example on how to do that.

To illustrate this, I am going to take a very quick example. If you have a table called Post, and want to query posts that have a certain pattern of title in a particular translation, then you may start to write the following:

Post.where(“title iLIKE ?”, "%#{pattern}%")

The following query will be executed:

SELECT \"posts\".* FROM \"posts\" WHERE (title LIKE 'TEST')

If you write the following, you will see the join being done as expected:

Post.with_translations(I18n.locale).where(“post_translations.title iLIKE ?”, "%#{pattern}%")

This will yield:

 SELECT \"posts\".* FROM \"posts\" INNER JOIN \"post_translations\" ON \"post_translations\".\"post_id\" = \"posts\".\"id\" WHERE \"post_translations\".\"title\" = 'Test' AND \"post_translations\".\"locale\" = 'en'

The key part of doing the join is with_translations(I18n.locale), which also searches in the locales that you have already set in your application.

Although this is just a quick method invocation, it is really helpful in cases when you are doing these types of queries.