如何将多个Rails SQL查询组合到rails中的单个查询中?

时间:2014-01-10 04:35:19

标签: mysql sql ruby-on-rails postgresql rails-activerecord

在我的rails代码中,我需要根据记录的日期和记录收到的投票的组合在表上运行查询。我在rails中完成了以下操作:

if params[:sort_by] == "default"
    objs1 = class_name.where("created_at between '#{Date.today - 7}' and '#{Date.today}' and net_votes > 0").order("net_votes DESC")
    objs2 = class_name.where("created_at between '#{Date.today - 30}' and '#{Date.today - 7}' and net_votes > 0").order("net_votes DESC")
    objs3 = class_name.where("created_at between '#{Date.today - 90}' and '#{Date.today - 30}' and net_votes > 0").order("net_votes DESC")
    objs4 = class_name.where("created_at < '#{Date.today - 90}' and net_votes > 0").order("net_votes DESC")
    objs = objs1 + objs2 + objs3 + objs4

除了效率之外,我不能在组合查询结果上使用分页,更不用说代码非常难看了。什么是正确的方法呢?

提前致谢。

2 个答案:

答案 0 :(得分:4)

使用order作为排序逻辑,而不是where

order_by_sql = <<-SQL
CASE WHEN created_at between '#{Date.today - 7}' and '#{Date.today}' THEN 1
     WHEN created_at between '#{Date.today - 30}' and '#{Date.today - 7}' THEN 2
     WHEN created_at between '#{Date.today - 90}' and '#{Date.today - 30}' THEN 3
     ELSE 4
END
SQL

objs = class_name.where('net_votes > 0').order(order_by_sql)

答案 1 :(得分:0)

您可以采取一些措施来使其更优雅,效果更佳:

1)将每个条件封装到范围中。例如,net_vtoes&gt; 0可重复使用:

def self.has_votes
  where("net_votes > 0")
end

def self.ordered 
  order("net_votes DESC")
end

def self.last_week
  where("created_at between '#{Date.today - 7}' and '#{Date.today}'")
end

2)根据Ryan Bates在此RailsCast中的建议创建一个范围运算符,以允许您以OR方式组合where条件:http://railscasts.com/episodes/355-hacking-with-arel?view=asciicast。这样就可以构建一个这样的语句:

(MyClass.last_week | MyClass.last_month).has_votes.ordered