如何在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())
我想获得类似的查询,但在活动记录中使用哪里。
答案 0 :(得分:49)
在Rails 3中,您可以使用:
YourModel.where(:created_at => start_date..end_date)
其中start_date
和end_date
是日期类。
答案 1 :(得分:9)
ActiveRecord
可以在接受BETWEEN
时使用Range
构建查询。这听起来可能更像你正在寻找的东西。
YourModel.where(created_at: 100.days.ago..100.days.from_now)
执行此操作似乎比在查询中使用>=
<=
更简单
答案 2 :(得分:7)
您没有指定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中,您将使用scope
和新的Arel范围方法:
scope :within_range, lambda { where("created_at <= ? AND created_at >= ?", Date.today + 100, Date.today - 100) }
答案 3 :(得分:1)
如果我理解,你需要这样的东西:
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