【问题标题】:List results by scope where (field) not nil THEN second condition按范围列出结果 where (field) not nil THEN 第二个条件
【发布时间】:2016-09-23 11:32:24
【问题描述】:

我想知道是否有一种方法可以进行一次查询以获得以下条件:

1) scope :scheduled_for, -> {where.not(:scheduled_for => nil)}

然后

2) scope :sort_by_position, -> {order('position')}

预期的结果将是以下列表:

  • 发布 1(9 月 23 日 && 职位 1)
  • 发布 2(9 月 24 日 && 职位 2)
  • 发布 3(位置:3)
  • 职位 4(职位:4)
  • 等等……

注意:位置字段可以是随机的(即帖子 1 的位置可能为 5,但由于它的 scheduled_for 不为空,它优先于较低位置的帖子。

【问题讨论】:

  • Model.scheduled_for.sort_by_position 有什么问题?这只会在访问结果时进行查询,所以它只会是一个查询。
  • 这仅给出部分结果,即带有 schedule_for 和 position NOT NIL 的帖子列表。它没有给出列表的第二部分(其中 schedule_for NIL 和 position NOT NIL)

标签: ruby-on-rails-4 named-scopes


【解决方案1】:

order_by可以指定多个条件

order_by('scheduled_for IS NULL, position')

scheduled_for IS NULL 如果为真则返回“1”,“0”为假,因此 NULL 值更大(即显示在列表末尾)

【讨论】:

    猜你喜欢
    • 2011-05-14
    • 2020-10-09
    • 1970-01-01
    • 2017-06-15
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 2021-12-22
    相关资源
    最近更新 更多