Skip to main content

i18n and Ransack

Ransack translation files are available in Ransack::Locale. You may also be interested in one of the many translations for Ransack available at http://www.localeapp.com/projects/2999.

Predicate and attribute translations in forms may be specified as follows (see the translation files in Ransack::Locale for more examples):

locales/en.yml:

en:
ransack:
asc: ascending
desc: descending
predicates:
cont: contains
not_cont: not contains
start: starts with
end: ends with
gt: greater than
lt: less than
models:
person: Passenger
attributes:
person:
name: Full Name
article:
title: Article Title
body: Main Content

Attribute names may also be changed globally, or under activerecord:

en:
attributes:
model_name:
model_field1: field name1
model_field2: field name2
activerecord:
attributes:
namespace/article:
title: AR Namespaced Title
namespace_article:
title: Old Ransack Namespaced Title

Working with Globalized Attributes

If you're using the Globalize gem for internationalized model attributes, you may encounter issues when sorting on translated attributes of associations while also joining the main model's translations.

For example, if you have a Book model with translated title and a Category model with translated name, sorting on the category's translated name while joining the book's translations may not work as expected:

# This may not work correctly:
Book.joins(:translations).ransack({ s: ['category_translations_name asc'] }).result

Workaround for Globalized Attributes Sorting

When working with globalized attributes and you need to sort on translated fields of associations, the simplest and most effective approach is to use the sort_link helper with the translation attribute directly:

<!-- This works perfectly for sorting on translated attributes -->
<%= sort_link @search, :translations_name %>
<%= sort_link @search, :category_translations_name %>

For programmatic sorting, let Ransack handle the joins first:

# Instead of joining translations first, let Ransack handle the joins:
search = Book.ransack({ s: ['category_translations_name asc'] })
results = search.result.joins(:translations)

# Or use the includes method to ensure all necessary translations are loaded:
search = Book.ransack({ s: ['category_translations_name asc'] })
results = search.result.includes(:translations, category: :translations)

# For more complex scenarios, you can manually specify the joins:
search = Book.ransack({ s: ['category_translations_name asc'] })
results = search.result
.joins(:translations)
.joins(category: :translations)

The key is to let Ransack establish the necessary joins for sorting first, then add any additional joins you need for the query.

This approach ensures that Ransack properly handles the complex join dependencies between your main model's translations and the associated model's translations.