【问题标题】:How to order a query by a translated field using globalize如何使用 globalize 按翻译字段排序查询
【发布时间】:2014-10-14 03:40:46
【问题描述】:

我正在尝试使用使用 globalize2 翻译的字段来订购查询。问题是,由于存储在数据库和关联中,我遇到了很多问题。

  • 包含翻译并按category_translations.name 排序不起作用。
  • 我尝试了一个 default_scope,但由于它不允许在条件下使用 lambda 或块,除非我将此补丁用于 ActiveRecord http://gist.github.com/81187,否则我无法使其正常工作
  • 我已经尝试使用 globalize2 中定义的 with_translations,但是我收到了一个错误,即使没有订购也无法让它工作。

我有类似的东西

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

  translates :name
end

问题是,如何按翻译名称排序?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    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

    【讨论】:

      【解决方案2】:

      我使用 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
      

      【讨论】:

      • 当然,作为 INNER JOIN,这假定所有类别都存在翻译。如果不是,则需要进行一些调整。
      • 感谢您的回复。是的,这是我尝试的第一件事,但由于并非所有翻译都存在无法解决我的问题...
      • 有更多时间做一个测试用例,试试这个最新版本。希望对您有所帮助!
      • 你没有奖励你的赏金。这没有帮助吗?
      • 当人们足够慷慨地抽出时间尝试提供帮助时,您可能希望保持领先。
      【解决方案3】:

      我假设任何名为Category 的模型最多有数百条记录,如果不是更少的话。也许您可以考虑在获取结果后在内存中对结果进行排序。

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

      不过要小心。如果categories 表包含超过数千条记录,这将成为一个坏主意。

      【讨论】:

      • 已经考虑过了...但我正在寻找一种更通用的机制,因为任何东西都应该订购,而不仅仅是类别:(
      • @msc bang 版本就地修改了数组。如果由于任何原因无法完成,您将收到错误消息。
      猜你喜欢
      • 2011-01-09
      • 2020-08-16
      • 2013-10-31
      • 2013-02-27
      • 2012-07-15
      • 1970-01-01
      • 2011-05-08
      • 2015-04-15
      • 1970-01-01
      相关资源
      最近更新 更多