红宝石 - 让记录过滤按日期 [英] ruby - getting records filtered by date
问题描述
我有一个作业模块(以及相应的表中分贝),该模块有一个字段名为scheduled_run(日期时间)和场名为user_id的:
- 我怎么可以得到所有属于一个用户,并定于今天?作业
- 我怎么可以得到所有属于一个用户,并计划于上周?作业
要得到所有的属于用户,并原定于今天的工作,你需要寻找的今天时间段之内的所有scheduled_runs:
用户= User.find(1)#会得到ID为1的用户
工作= Job.where(user_ID的=:标识和scheduled_run> =:启动和scheduled_run<:结束,
:ID =>用户帐号,
:启动=> Date.today,
:年底=> 1.day.from_now.to_date)
要获得上周所有的工作,我们会做一个类似的命令,但我们会切换:启动
和:结束
是一周的开始和结束:
用户= User.find(1)#会得到ID为1的用户
工作= Job.where(user_ID的=:标识和scheduled_run> =:启动和scheduled_run<:结束,
:ID =>用户帐号,
:启动=> 1.week.ago.to_date,
:年底=> Date.today)
在以上两个命令, TO_DATE
将导致的ActiveRecord
治疗所产生的日期时间
作为一天的开始。
i have a "Job" module (and corresponding table in the db), that module have a field called scheduled_run (datetime) and a field called user_id:
- how can i get all the jobs that belongs to a user and are scheduled for today?
- how can i get all the jobs that belongs to a user and are scheduled for last week?
To get all the jobs that belong to a user and are scheduled for today, you'll need to search for all scheduled_runs within the today time period:
user = User.find(1) # Will get the user with ID 1
jobs = Job.where("user_id = :id AND scheduled_run >= :start AND scheduled_run < :end",
:id => user.id,
:start => Date.today,
:end => 1.day.from_now.to_date)
To get all the jobs for last week, we'll do a similar command, but we'll switch :start
and :end
to be the start and end of the week:
user = User.find(1) # Will get the user with ID 1
jobs = Job.where("user_id = :id AND scheduled_run >= :start AND scheduled_run < :end",
:id => user.id,
:start => 1.week.ago.to_date,
:end => Date.today)
In both of the above commands, to_date
will cause ActiveRecord
to treat the resulting DateTime
as beginning of day.
这篇关于红宝石 - 让记录过滤按日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!