How to order a query by a translated field using globalize

Viewed 4129

I'm trying to order a query using a field which is translated with globalize2. The problem is that since stored in database and in an association I'm having lot of problems.

  • Doing an include of the translations and ordering by category_translations.name doesn't work.
  • I tried a default_scope but since it doesn't allow to use lambda or a block for the conditions I can't get it working unless I use this patch for ActiveRecord http://gist.github.com/81187
  • I've tried with the with_translations defined in globalize2, however I get an error with this and I couldn't get it to work even without ordering.

I've something like that

class Category < ActiveRecord::Base
  validates_presence_of :name
  validates_uniqueness_of :name
  has_many :products, :dependent => :destroy

  translates :name
end

The question is, how do I order by the translated name?

3 Answers

I'm assuming that any model called Category would have at most hundreds of records if not less. Maybe you can consider sorting the results in memory, after fetching them.

@categories = Category.all # or whatever else to retrieve what you want
@categories.sort! { |a,b| a.name <=> b.name }

Beware though. This would become a bad idea if the categories table contains more than thousands of records.

Related