微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

在我的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

除了效率,我不能对组合查询结果使用分页,更不用说代码很丑陋了.正确的方法是什么?

提前致谢.

解决方法:

将命令用于排序逻辑,而不是在以下位置:

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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐