Home » Ruby » Active Record – Find records which were created_at before today

Active Record – Find records which were created_at before today

Posted by: admin November 30, 2017 Leave a comment

Questions:

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)
Answers:

Using the standard ActiveRecord:

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

Using the underlying Arel interface:

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

Using a thin layer over Arel:

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

Using library squeel:

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

Questions:
Answers:

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 :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 documentation or source code. This scope doesn’t break the where chain. This means you can also do:

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

Questions:
Answers:

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