ActiveRecord-查找在今天之前创建的记录

我想获取 create _ at 字段小于今天(一个日期)的所有记录。 有没有这样的东西:

MyTable.find_by_created_at(< 2.days.ago)
68839 次浏览

Using ActiveRecord the standard way:

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

Using the underlying Arel interface:

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

Using some thin layer over Arel:

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

Using squeel:

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

Another way is to create a scope in MyModel or in ApplicationRecord using the Arel interface like tokland sugensted in his answer like so:

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

Example usage of the scope:

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

For all predications, check the documentation or source code. This scope doesn't break the where chain. This means you can also do:

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

To get all records of MyTable created up until 2 days ago:

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 MyTable with an event_date at least 2 days from now:

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