红宝石 - 让记录过滤按日期 [英] ruby - getting records filtered by date

查看:128
本文介绍了红宝石 - 让记录过滤按日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个作业模块(以及相应的表中分贝),该模块有一个字段名为scheduled_run(日期时间)和场名为user_id的:

  1. 我怎么可以得到所有属于一个用户,并定于今天?作业
  2. 我怎么可以得到所有属于一个用户,并计划于上周?作业
解决方案

要得到所有的属于用户,并原定于今天的工作,你需要寻找的今天时间段之内的所有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:

  1. how can i get all the jobs that belongs to a user and are scheduled for today?
  2. 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屋!

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