如何在具有可变日期的Rails中搜索日期范围

我怎么能在rails active record中做到这一点?

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

编辑:好的,对不起,这不是我在Rails 3.0方式中的活动记录中要做的事情:

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()) 

我想得到一个类似的查询,但使用活动记录中的位置。

你没有指定Rails 2或3,我不完全确定你真正想要的范围,但这应该让你开始。 请添加一些示例日期,并说明它们是否应该属于您的范围。

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

 # 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中,您将使用具有新Arel范围方法的范围:

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

在Rails 3中,您可以使用:

 YourModel.where(:created_at => start_date..end_date) 

其中start_dateend_date是Date类。

ActiveRecord可以在接受Range时使用BETWEEN构建查询。 这听起来可能更像你正在寻找的东西。

YourModel.where(created_at: 100.days.ago..100.days.from_now)

这样做总比在查询中使用>= <=更简单一些

如果我理解,你需要这样的东西:

 date = Date.today after = date.start_of_month - 100 before = date.end_of_month - 100 YourModel.find(:all, :conditions => ['created_at > ? AND created_at < ?', after, before]) 

或在范围内(轨道2):

 # shorter name is needed named_scope :created_100_days_before_this_month, lambda do |date| after = date.start_of_month - 100 before = date.end_of_month - 100 YourModel.find(:all, :conditions => ['created_at > ? AND created_at < ?', after, before]) end