导轨为作用域添加顺序



我有一个 Rails 3.2 应用程序,其工作范围基于关联模型中的字段:

scope :maintenance, -> { joins(:costcat).where(costcats: { maintenance: true }) }

我希望结果按costcats.position排序。

我试过这些:

scope :maintenance, -> { joins(:costcat).where(costcats: { maintenance: true }).order(costcats.position ASC) }
scope :maintenance, -> { joins(:costcat).where(costcats: { maintenance: true }) }, :order => "costcats.position ASC"

感谢您的帮助!

UPDATE1

有了建议的答案,我得到了以下SQL:

SELECT "costestimates".* FROM "costestimates" INNER JOIN "costcats" ON "costcats"."id" = "costestimates"."costcat_id" WHERE "costestimates"."costproject_id" = 1 AND "costcats"."maintenance" = 't' ORDER BY id ASC, position ASC

如果id ASC不在订单中,它会起作用

UDDATE2

我的错,我不得不删除默认的范围顺序costestimates

scope :maintenance, 
      ->{ joins(:costcat).where(costcats: { maintenance: true }).order("costcats.position")}

我喜欢使用#merge,因为它使查询看起来更干净

scope :maintenance, ->{ joins(:costcat)
                         .merge(
                           Costcat.where(maintenance: true).order(:position)
                         )
                       }

PS:多行仅用于可读性

最新更新