93
votes

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

MyTable.find_by_created_at(< 2.days.ago)
5

5 Answers

184
votes

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 }
13
votes

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)
3
votes

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
-1
votes

Using ActiveRecord -> To see all users that were created up until 1 day ago:

User.where('created_at < ?', Time.current - 1.days)
-36
votes

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

@users = User.all

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