ruby-on-rails-3 – 多个日期范围内的Rails 3查询

ruby-on-rails-3 – 多个日期范围内的Rails 3查询,第1张

概述假设我们有一些日期范围,例如: ranges = [ [(12.months.ago)..(8.months.ago)], [(7.months.ago)..(6.months.ago)], [(5.months.ago)..(4.months.ago)], [(3.months.ago)..(2.months.ago 假设我们有一些日期范围,例如:

ranges = [          [(12.months.ago)..(8.months.ago)],[(7.months.ago)..(6.months.ago)],[(5.months.ago)..(4.months.ago)],[(3.months.ago)..(2.months.ago)],[(1.month.ago)..(15.days.ago)]         ]

和一个Post模型:created_at属性.

我想查找created_at值在此范围内的帖子,因此我们的目标是创建一个类似的查询

SELECT * FROM posts WHERE created_at     BETWEEN '2011-04-06' AND '2011-08-06' OR    BETWEEN '2011-09-06' AND '2011-10-06' OR    BETWEEN '2011-11-06' AND '2011-12-06' OR    BETWEEN '2012-01-06' AND '2012-02-06' OR    BETWEEN '2012-02-06' AND '2012-03-23';

如果您只有一个这样的范围:

range = (12.months.ago)..(8.months.ago)

我们可以做这个查询:

Post.where(:created_at => range)

和查询应该是:

SELECT * FROM posts WHERE created_at     BETWEEN '2011-04-06' AND '2011-08-06';

有没有办法使用像这个Post.where(:created_at =>范围)这样的符号来进行此查询?

构建此查询的正确方法是什么?

谢谢

解决方法 对于帕伦来说,它有点激进,但准备潜入这个兔子洞

ranges = [          ((12.months.ago)..(8.months.ago)),((7.months.ago)..(6.months.ago)),((5.months.ago)..(4.months.ago)),((3.months.ago)..(2.months.ago)),((1.month.ago)..(15.days.ago))         ]table = Post.arel_tablequery = ranges.inject(table) do |sum,range|  condition = table[:created_at].in(range)  sum.class == Arel::table ? condition : sum.or(condition)end

然后,query.to_sql应该相等

(((("sessions"."created_at" BETWEEN '2011-06-05 12:23:32.442238' AND '2011-10-05 12:23:32.442575' OR "sessions"."created_at" BETWEEN '2011-11-05 12:23:32.442772' AND '2011-12-05 12:23:32.442926') OR "sessions"."created_at" BETWEEN '2012-01-05 12:23:32.443112' AND '2012-02-05 12:23:32.443266') OR "sessions"."created_at" BETWEEN '2012-03-05 12:23:32.443449' AND '2012-04-05 12:23:32.443598') OR "sessions"."created_at" BETWEEN '2012-05-05 12:23:32.443783' AND '2012-05-21 12:23:32.443938')

你应该能够做Post.where(查询)

编辑

你也可以这样做:

range_conditions = ranges.map{|r| table[:created_at].in(r)}query = range_conditions.inject(range_conditions.shift,&:or)

保持一点简洁

@H_419_78@ 总结

以上是内存溢出为你收集整理的ruby-on-rails-3 – 多个日期范围内的Rails 3查询全部内容,希望文章能够帮你解决ruby-on-rails-3 – 多个日期范围内的Rails 3查询所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1280479.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-09
下一篇 2022-06-09

发表评论

登录后才能评论

评论列表(0条)

保存