globalize/globalize

Duplicated rows when ordering and using Globalize Fallbacks

brenes opened this issue · 1 comments

We are having an issue with orderings and Globalize fallbacks when upgrading Globalize to 6.0.1. The issue is quite simple but I'm not sure of the right solution.

We have a model Book with a translated attribute title. And also have configured Globalize fallbacks:

Globalize.fallbacks = {
  :es => [:es, :en],
  :en => [:en, :es],
  :de => [:de, :en, :es]
}

When we do Book.order(:title) we get the following SQL

SELECT DISTINCT "books".*, "book_translations"."title" FROM "books" INNER JOIN "book_translations" ON "book_translations"."book_id" = "books"."id" WHERE "book_translations"."locale" IN ($1, $2) ORDER BY "book_translations"."title" ASC  [["locale", "en"], ["locale", "es"]]

The issue here is that we have duplicated instances of the books when the translated attribute is not the same (which I guess is common), so we don't really have the books ordered by title.

Book.count # 100
Book.order(:title).length # 180
Book.all.sort_by(&:title).length # 100

As I said at the beginning, I'm not sure of the right solution here because:

  • I expect Book.order(:title) to be equal to Book.all.sort_by(&:title) and that fallbacks are used in the application if the title in some language is empty (exactly like the sort_by solution does).
  • But we can't do that and then allowing some other scope to be chained after the order, unless somehow the order is executed after the rows are retrieved from the database doing the ordering in Rails.

Same thing goes for pluck, reorder...

Since this issue only appears when Fallbacks are configured, should we include it into the Fallbacks documentation so the developers who may use them are aware and not use the order method?

Is there any solution that we may have missed?

@brenes We came across the same problem and using an includes(:translations) somewhat weirdly fixes it for us, so perhaps try:

Book.includes(:translations).order(:title)

By using the includes we get the id appearing in the distinct clause ie

SELECT DISTINCT "books".*, "book_translations"."title", "books"."id"...