Rails将命令添加到范围

时间:2015-04-28 15:13:58

标签: ruby-on-rails

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

self.searchController.hidesNavigationBarDuringPresentation = NO;
self.searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;

// Include the search bar within the navigation bar.
self.navigationItem.titleView = self.searchController.searchBar;

self.definesPresentationContext = YES;

我希望结果按scope :maintenance, -> { joins(:costcat).where(costcats: { maintenance: true }) } 排序。

我试过这些:

costcats.position

感谢您的帮助!

UPDATE1

根据建议的答案,我得到以下SQL:

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

如果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 不在ORDER

中,它会起作用

UDDATE2

我的不好,我不得不删除id ASC

中的默认范围顺序

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

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

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

PS:多行仅用于提高可读性