views:

85

answers:

1

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?

A: 

I tested this using sqlite3, and it works.

class Category < ActiveRecord::Base
  ...
  named_scope :ordered, lambda {|locale|
    {
      #:select => "categories.*, categories.name sort_name",
      # For MySQL
      #:select => "categories.*, IF(category_translations.name IS NULL, categories.name, category_translations.name) sort_name",
      # For sqlite3
      :select => "categories.*, (CASE WHEN category_translations.name IS NULL THEN categories.name ELSE category_translations.name END) sort_name",
      :joins => ActiveRecord::Base.sanitize_sql_array([
        "LEFT JOIN category_translations on category_translations.category_id = categories.id AND category_translations.locale = ?", locale]),
      :order => "sort_name"
    }
  }
  ...
end

Category.ordered(some_locale).all # Returns all records, sorted by translated name
fullware
Of course being an INNER JOIN this assumes that translations exist for all categories. If not it'll need some tweaks.
fullware
Thanks for your response. Yes, that's the first thing I tried, but since not all the translations exists that didn't solve my problem...
Francisco
Had a bit more time for a test case, give this latest version a go. Hope it helps!
fullware
You didn't award your bounty. Was this not helpful?
fullware
Sorry, but didn't noticed the edition :(
Francisco
You might want to stay on top of that, when people are generous enough to make time to try to help.
fullware