Active Record - Find records which were created_at before today

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 }

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)

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