Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active Record - Find records which were created_at before today

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)
like image 299
Sayuj Avatar asked Nov 02 '11 09:11

Sayuj


3 Answers

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 }
like image 172
tokland Avatar answered Nov 15 '22 12:11

tokland


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)
like image 45
Andreas Avatar answered Nov 15 '22 14:11

Andreas


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
like image 30
3limin4t0r Avatar answered Nov 15 '22 13:11

3limin4t0r