从rails 3升级到rails 4时,has_many关联的顺序错误

st3*_*fan 5 ruby postgresql sql-order-by has-many-through ruby-on-rails-4

我正在尝试将一个项目从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
Run Code Online (Sandbox Code Playgroud)

当我调用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
Run Code Online (Sandbox Code Playgroud)

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

查询更改为:

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

它在order子句中添加了代码,这使得PostgreSQL通过错误.我认为这是因为范围,但我无法弄清楚如何获得ORDER BY代码.

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

st3*_*fan 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
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅https://github.com/rails/rails/issues/12719