Active Record - Find records which were created_at before today

RubyActiverecord

Ruby Problem Overview


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)

Ruby Solutions


Solution 1 - Ruby

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 }

Solution 2 - Ruby

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)

Solution 3 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSayujView Question on Stackoverflow
Solution 1 - RubytoklandView Answer on Stackoverflow
Solution 2 - RubyAndreasView Answer on Stackoverflow
Solution 3 - Ruby3limin4t0rView Answer on Stackoverflow