首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从rails 3升级到rails 4时has_many关联的错误顺序

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

Stack Overflow用户
提问于 2013-10-31 15:30:21
回答 2查看 2K关注 0票数 5

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

代码语言:javascript
复制
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中执行以下查询:

代码语言:javascript
复制
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进行了如下更新:

代码语言:javascript
复制
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

查询更改为:

代码语言:javascript
复制
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通过一个错误。我认为这是因为范围的原因,但我不知道如何通过代码来获取订单。

任何帮助都是感激的,谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-10-31 20:40:09

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

代码语言:javascript
复制
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

票数 4
EN

Stack Overflow用户

发布于 2013-10-31 15:46:29

tint_types关联更改为

代码语言:javascript
复制
has_many :tint_types, -> { reorder('value').uniq }, :through => :tint_codes
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19710639

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档