Ruby-on-rails 两次之间的 Rails 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10778624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:27:39  来源:igfitidea点击:

Rails query between two times

ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1

提问by Kyle Decot

I have a rails app that has a Checkinmodel. I want to find all records that are within a specific time range for the current day. How would I write a whereto get all records that were created between 12PM and 4:30PM?

我有一个带有Checkin模型的 rails 应用程序。我想查找当天特定时间范围内的所有记录。我将如何编写一个where来获取在 12PM 到 4:30PM 之间创建的所有记录?

回答by Ismael Abreu

@x1a4's answer should be good for you but you can do it in a more readable and shorter way, using a range.

@x1a4 的答案应该对您有好处,但您可以使用范围以更具可读性和更短的方式进行回答。

 Checkin.where(created_at: Time.parse("12pm")..Time.parse("4:30pm"))

It should generate something like:

它应该生成如下内容:

SELECT "checkins".*
FROM "checkins" 
WHERE ("checkins"."created_at" BETWEEN '2012-05-28 12:00:00.000000' AND '2012-05-28 16:30:00.000000')

You can change Time.parse("12pm")with any other way to create a time.

您可以更改Time.parse("12pm")任何其他方式来创建时间。

回答by x1a4

This looks like it would work, assuming UTC time zone:

假设 UTC 时区,这看起来可行:

Record.where('created_at > ? AND created_at < ?', Date.today + 12.hours, Date.today + 16.5.hours)

or with a BETWEEN:

或带有BETWEEN

Record.where('created_at BETWEEN ? AND ?', Date.today + 12.hours, Date.today + 16.5.hours)

BETWEENmay or not may include the second value in the range. Postgres includes it.

BETWEEN可能包括也可能不包括范围内的第二个值。Postgres 包括它

回答by Jenorish

You could use below gem to find the records between dates,

您可以使用下面的 gem 来查找日期之间的记录,

This gemquite easy to use and more clear [By star][1]. I'm using this gem and the API is more clear and the documentation is also well explained.

这颗宝石非常易于使用且更清晰 [按星级] [1]。我正在使用这个 gem,API 更清晰,文档也得到了很好的解释。

Post.between_times(
 Time.zone.now - 3.hours,  # all posts in last 3 hours
 Time.zone.now
)

Here you could pass our field also Post.by_month("January", field: :updated_at)

在这里你也可以通过我们的领域 Post.by_month("January", field: :updated_at)

Please see the documentation and try it.

请查看文档并尝试。