【问题标题】:Wrong order on has_many association when upgrading from rails 3 to rails 4从 rails 3 升级到 rails 4 时 has_many 关联的错误顺序
【发布时间】:2013-11-11 16:51:07
【问题描述】:

我正在尝试将一个项目从 Rails 3 更新到 Rails 4。在 Rails 3 中我正在做:

class Sale < ActiveRecord::Base
  has_many :windows, :dependent => :destroy
  has_many :tint_codes, :through => :windows, :uniq => true, :order => 'code ASC'
  has_many :tint_types, :through => :tint_codes, :uniq => true, :order => 'value ASC'
end

当我调用 sale.tint_types 时,它在 Rails 3 中执行以下查询:

SELECT DISTINCT "tint_types".* FROM "tint_types" INNER JOIN "tint_codes" ON "tint_types"."id" = "tint_codes"."tint_type_id" INNER JOIN "windows" ON "tint_codes"."id" = "windows"."tint_code_id" WHERE "windows"."sale_id" = 2 ORDER BY value ASC

我为 Rails 4 更新了它,如下所示:

class Sale < ActiveRecord::Base
  has_many :windows, :dependent => :destroy
  has_many :tint_codes, -> { order('code').uniq }, :through => :windows
  has_many :tint_types, -> { order('value').uniq }, :through => :tint_codes
end

查询变为:

SELECT DISTINCT "tint_types".* FROM "tint_types" INNER JOIN "tint_codes" ON "tint_types"."id" = "tint_codes"."tint_type_id" INNER JOIN "windows" ON "tint_codes"."id" = "windows"."tint_code_id" WHERE "windows"."sale_id" = $1  ORDER BY value, code

它在 order 子句中添加 code,这使 PostgreSQL 出错。我认为这是因为范围的原因,但我不知道如何获取 ORDER BY 代码。

任何帮助表示赞赏, 谢谢!

【问题讨论】:

  • 试试unscoped.order('value').uniq
  • 已经试过了。不工作。看起来它首先设置了 tint_types 的顺序,然后设置了 tint_codes 的顺序。

标签: ruby postgresql ruby-on-rails-4 sql-order-by has-many-through


【解决方案1】:

Rails 社区帮助我找到了解决方案。

class Sale < ActiveRecord::Base
  has_many :windows, :dependent => :destroy
  has_many :tint_codes, -> { order('code').uniq }, :through => :windows
  has_many :tint_types, -> { uniq }, :through => :tint_codes

  def tint_types
    super.reorder(nil).order(:width => :asc)
  end
end

更多详情请见https://github.com/rails/rails/issues/12719

【讨论】:

    【解决方案2】:

    tint_types 关联更改为

    has_many :tint_types, -> { reorder('value').uniq }, :through => :tint_codes
    

    【讨论】:

    • 它执行的查询与我仅使用 order 时的查询相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-18
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多