5

我正在尝试将一个项目从 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 子句中添加代码,这会使 PostgreSQL 出错。我认为这是因为范围,但我不知道如何获取 ORDER BY 代码。

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

4

2 回答 2

4

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

于 2013-10-31T20:40:09.077 回答
1

tint_types将关联更改为

has_many :tint_types, -> { reorder('value').uniq }, :through => :tint_codes
于 2013-10-31T15:46:29.327 回答