如何每天查找具有最大值(在关联模型中定义)的记录

时间:2019-03-27 21:34:10

标签: ruby-on-rails ruby-on-rails-4 activerecord

我想每天获取最高优先级的所有记录(在相关模型中定义)

我正在努力用activerecord(rails 4.2)构建它

问题很与此相似 Get records with max value for each group of grouped SQL results 除了年龄来自第二个模型

还是这个 with activerecord how can I select records based on the highest value of a field?

Model 1: Workduration: 
    date, duration 
    belongs_to :timerule

Model 2: Timerule: 
    priority
    has_many :workdurations

我将数据汇总如下(全部在工作期间)

def self.withPrio
    select("workdurations.*, timerules.prio AS prio").joins(:timerule)
end

我找不到在其上建立LEFT OUTER JOIN(自我联接)的正确方法。

尝试并错误代码:

Workduration.withPrio.joins("left join ? workdurations.date = wd2.date and workdurations.prio < wd2.prio", Workduration.withPrio)

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我最终通过(一个大)find_by_sql和第二个查询来做到这一点,以保持范围可链接:

  scope :maxPrioIds, ->{find_by_sql('SELECT o.*
                                  FROM
                                    (SELECT  workdurations.*, timerules.prio AS prio FROM "workdurations" INNER JOIN "timerules" ON "timerules"."id" = "workdurations"."timerule_id") o
                                  LEFT JOIN (SELECT  workdurations.*, timerules.prio AS prio FROM "workdurations" INNER JOIN "timerules" ON "timerules"."id" = "workdurations"."timerule_id") b
                                  ON o.date = b.date AND o.prio < b.prio
                                  WHERE b.prio is NULL').map(&:id)}
  scope :relevant, -> {where(id: Workduration.maxPrioIds)}