如何在具有可变日期的 Rails 中搜索日期范围 [英] How can I search date range in Rails with variable date

查看:17
本文介绍了如何在具有可变日期的 Rails 中搜索日期范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Rails 活动记录中执行此操作?

How can I do this in rails active record¿?

查找所有匹配的模型(created_at + 本月之间的 100 天)

find all models that match (created_at + 100 days between this month)

好的,对不起,我在 Rails 3.0 方式中尝试在活动记录中做的事情不准确:

Ok, Sorry for not be precise this what I'm trying to do in active record in Rails 3.0 way:

select 
    distinct p.ID 
from
    patients p
    inner join vaccines_patients vp on p.ID = vp.patient_id
    inner join vaccines v on v.ID = vp.VACCINE_ID
where
    month(vp.appliedAt + INTERVAL v.duration DAY) = month(now())

我想获得类似的查询,但使用活动记录中的位置.

I want to get a similar query but using where in active record.

推荐答案

您没有指定 Rails 2 或 3,我不完全确定您实际要寻找的范围,但这应该可以帮助您入门.请添加一些示例日期并说明它们是否应该在您的范围内.

You didn't specify Rails 2 or 3, and I'm not entirely sure what range you're actually looking for, but this should get you started. Please add some example dates and say whether they should fall into your range or not.

在 Rails 2 中,您可以在模型中使用 named_scope.

In Rails 2 you can use a named_scope in your model.

# This range represents "created_at" values that are within 100 days on either side of today.
# Please clarify what "created_at + 100 days between this month" means if you need help
# refining this.
#
named_scope :within_range, lambda {{ :conditions => ["created_at <= ? AND created_at >= ?", Date.today + 100, Date.today - 100] }}

在 Rails 3 中,您将使用 scope 和新的 Arel 范围方法:

In Rails 3, you would use a scope with the new Arel scope methods:

scope :within_range, lambda { where("created_at <= ? AND created_at >= ?", Date.today + 100, Date.today - 100) }

这篇关于如何在具有可变日期的 Rails 中搜索日期范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆