如何DRY链接ActiveRecord调用

时间:2013-12-29 00:21:15

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

考虑这段代码:

if ids.blank?
  UptimeSummary.
    where("start_time >= ?", start_time).
    group(:uptime_monitor_id).
    select("uptime_monitor_id, sum(uptime)/count(*) AS uptime_average")
else
  UptimeSummary.
    where(:uptime_monitor_id => ids).
    where("start_time >= ?", start_time).
    group(:uptime_monitor_id).
    select("uptime_monitor_id, sum(uptime)/count(*) AS uptime_average")
end

这两个条款之间的唯一区别是后一条款中的附加(:uptime_monitor_id => ids)

这似乎相当不干。我怎样才能清理它?

1 个答案:

答案 0 :(得分:0)

我在输入问题时想出了答案。由于对ActiveRecord查询链的调用是延迟的,因此您可以这样做:

q = UptimeSummary.
      where("start_time >= ?", start_time).
      group(:uptime_monitor_id).
      select("uptime_monitor_id, sum(uptime)/count(*) AS uptime_average")
q = q.where(:uptime_monitor_ids => ids) unless ids.blank?

如果您知道更清洁的方法,我很乐意了解它。