|
51 | 51 | namespace_article:
|
52 | 52 | title: Old Ransack Namespaced Title
|
53 | 53 | ```
|
| 54 | + |
| 55 | +## Working with Globalized Attributes |
| 56 | + |
| 57 | +If you're using the [Globalize gem](https://github.com/globalize/globalize) for internationalized model attributes, you may encounter issues when sorting on translated attributes of associations while also joining the main model's translations. |
| 58 | + |
| 59 | +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: |
| 60 | + |
| 61 | +```ruby |
| 62 | +# This may not work correctly: |
| 63 | +Book.joins(:translations).ransack({ s: ['category_translations_name asc'] }).result |
| 64 | +``` |
| 65 | + |
| 66 | +### Workaround for Globalized Attributes Sorting |
| 67 | + |
| 68 | +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: |
| 69 | + |
| 70 | +```erb |
| 71 | +<!-- This works perfectly for sorting on translated attributes --> |
| 72 | +<%= sort_link @search, :translations_name %> |
| 73 | +<%= sort_link @search, :category_translations_name %> |
| 74 | +``` |
| 75 | + |
| 76 | +For programmatic sorting, let Ransack handle the joins first: |
| 77 | + |
| 78 | +```ruby |
| 79 | +# Instead of joining translations first, let Ransack handle the joins: |
| 80 | +search = Book.ransack({ s: ['category_translations_name asc'] }) |
| 81 | +results = search.result.joins(:translations) |
| 82 | +
|
| 83 | +# Or use the includes method to ensure all necessary translations are loaded: |
| 84 | +search = Book.ransack({ s: ['category_translations_name asc'] }) |
| 85 | +results = search.result.includes(:translations, category: :translations) |
| 86 | +
|
| 87 | +# For more complex scenarios, you can manually specify the joins: |
| 88 | +search = Book.ransack({ s: ['category_translations_name asc'] }) |
| 89 | +results = search.result |
| 90 | + .joins(:translations) |
| 91 | + .joins(category: :translations) |
| 92 | +``` |
| 93 | + |
| 94 | +The key is to let Ransack establish the necessary joins for sorting first, then add any additional joins you need for the query. |
| 95 | + |
| 96 | +This approach ensures that Ransack properly handles the complex join dependencies between your main model's translations and the associated model's translations. |
0 commit comments