ruby Active Record - 查找今天之前 created_at 的记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7978018/
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-06 04:26:31  来源:igfitidea点击:

Active Record - Find records which were created_at before today

rubyactiverecord

提问by Sayuj

I want to get all records where the created_at field is less than today (a date). Is there anything like:

我想获取 created_at 字段小于今天(日期)的所有记录。有没有类似的东西:

MyTable.find_by_created_at(< 2.days.ago)

回答by tokland

Using ActiveRecordthe standard way:

以标准方式使用ActiveRecord

MyModel.where("created_at < ?", 2.days.ago)

Using the underlying Arelinterface:

使用底层Arel接口:

MyModel.where(MyModel.arel_table[:created_at].lt(2.days.ago))

Using a thin layerover Arel:

在 Arel 上使用薄层

MyModel.where(MyModel[:created_at] < 2.days.ago)

Using squeel:

使用squeel

MyModel.where { created_at < 2.days.ago }

回答by Andreas

To get all records of MyTablecreated up until 2 days ago:

要获取MyTable2 天前创建的所有记录:

MyTable.where(created_at: Date.new..2.days.ago)

Note that you can also look for records with fields containing fields in the future in similar way, i.e. to get all records of MyTablewith an event_dateat least 2 days from now:

请注意,您也可以寻找记录包含的字段在类似的方式对未来的字段,即获得的所有记录MyTableevent_date至少2天从现在开始:

MyTable.where(event_date: 2.days.from_now..DateTime::Infinity.new)

回答by 3limin4t0r

Another way is to create a scope in MyModelor in ApplicationRecordusing the Arelinterface like toklandsugensted in his answerlike so:

另一种方法是创建一个范围MyModelApplicationRecord使用阿雷尔一样的界面tokland在sugensted他的回答像这样:

scope :arel, ->(column, predication, *args) { where(arel_table[column].public_send(predication, *args)) }

Example usage of the scope:

范围的示例用法:

MyModel.arel(:created_at, :lt, 2.days.ago)

For all predications, check the documentationor source code. This scope doesn't break the wherechain. This means you can also do:

对于所有谓词,请检查文档源代码。此范围不会破坏where链条。这意味着您还可以执行以下操作:

MyModel.custom_scope1.arel(:created_at, :lt, 2.days.ago).arel(:updated_at, :gt, 2.days.ago).custom_scope2

回答by Homer Jon

Time.now refers to right now or this very second. So to find all users before right now just use

Time.now 指的是现在或这一秒。所以现在要找到所有用户,只需使用

@users = User.all

This will find all users before right now and will exclude future users or users that join after Time.now

这将找到之前的所有用户,并排除未来的用户或在 Time.now 之后加入的用户