Active Record - Find Records Which Were Created_At Before Today

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 }

Find records that were created closest to the current date

You could find the closest record in the past with something like:

Record.where("created_at <= ?", Date.today).order_by("created_at DESC").limit(1)

Similarly, you can have the closest record in the future

Record.where("created_at >= ?", Date.today).order_by("created_at ASC").limit(1)

And then compare wich one is the closest to current date...

There may be a solution to do it with a single request, but I could not find how (if you're using SQL server, there's a method DATEDIFF that could help).

Update: Thanks to Mischa

If you're sure that all created_atare in the past, you're looking to the last created record, that could be written

Record.order("created_at").last

Update

To get all the records created the same date then the last record:

last_record_date = Record.max(:created_at)
Record.where(:created_at => (last_record_date.at_beginning_of_day)..(last_record_date.end_of_day))

Find Most Recent Rails Record In Past

Check this

Plan.where("created_at > ?", Time.now.beginning_of_week).order("week_starting").last

How to get record created today by rails activerecord?

Post.where(created_at: Time.zone.now.beginning_of_day..Time.zone.now.end_of_day)

PS: This answer has been modified as answer by Harish Shetty was better than mine. As my answer is accepted one. I have updated this answer for community support

Find last created_at record

That's a valid request

Record.order(created_at: :desc).first

take care of a tree index on this field to have a better performance, though

How to get yesterday data from Rails ActiveRecord

Meet.where("DATE(created_at) = ?", Date.today-1)

Rails ActiveRecord Find / Search by Date

selected_date = Date.parse(params[:selected_date])
# This will look for records on the given date between 00:00:00 and 23:59:59
sh = SupportHistory.where(
:created_at => selected_date.beginning_of_day..selected_date.end_of_day)

Time Zones may be a concern you need to look into, but this should work if all your times are in the same time zone.



Related Topics



Leave a reply



Submit