【发布时间】: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