代码之家  ›  专栏  ›  技术社区  ›  st3fan

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

  •  5
  • st3fan  · 技术社区  · 11 年前

    我正在尝试将一个项目从Rails3更新到Rails4。在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时,它在Rails3中执行以下查询:

    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通过了一个错误。我认为这是因为作用域的原因,但我不知道如何获得ORDERBY代码。

    感谢任何帮助, 谢谢

    2 回复  |  直到 6 年前
        1
  •  4
  •   st3fan    11 年前

    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
  •  1
  •   Gerry    11 年前

    更改 tint_types 与的关联

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