如何使用globalize按翻译字段排序查询

Fra*_*ran 15 activerecord ruby-on-rails

我正在尝试使用通过globalize2转换的字段来订购查询.问题是,由于存储在数据库和协会中,我遇到了很多问题.

  • 执行包含翻译和排序是category_translations.name不起作用的.
  • 我尝试了一个default_scope,但因为它不允许使用lambda或块来处理条件,所以除非我在ActiveRecord中使用这个补丁,否则我无法使用它.http://gist.github.com/81187
  • 我已尝试使用with_translationsglobalize2中的定义,但是我得到了一个错误,即使没有订购也无法让它工作.

我有类似的东西

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

  translates :name
end
Run Code Online (Sandbox Code Playgroud)

问题是,我如何按翻译名称订购?

reb*_*tte 13

with_translations方法似乎要走了:

Category.with_translations(I18n.locale).order('category_translations.name')

此外,如果您正在使用PostgreSQL,您可能希望添加不区分大小写的顺序:

Category.with_translations(I18n.locale).order("LOWER(category_translations.name) ASC")

更多相关信息:https: //github.com/globalize/globalize#scoping-objects-by-those-with-translations


ace*_*des 1

我使用 sqlite3 对此进行了测试,并且它有效。

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
Run Code Online (Sandbox Code Playgroud)