Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get yesterday data from Rails ActiveRecord

If I have a meet Model in Rails,now I want to get the record yesterday,how should I do?

Meet.where(:created_at=> ) # what should I write here?

Or ActiveRecord comes with some method to filter the yesterday record?

like image 362
HXH Avatar asked Dec 24 '13 05:12

HXH


3 Answers

Meet.where("DATE(created_at) = ?", Date.today-1)
like image 61
Bharat soni Avatar answered Sep 27 '22 20:09

Bharat soni


Here is a slightly more generic approach, using Arel and scopes:

  scope :created_since, (
    lambda do |time|
      where(Meet.arel_table[:created_at].gteq(time))
    end
  )

Meet.created_since(1.day.ago).count
like image 33
Dan Kohn Avatar answered Sep 27 '22 22:09

Dan Kohn


If you are using Rails 5.1 or later you can use all_day:

Meet.where(created_at: 1.day.ago.all_day)

also.. I suggest to define a scope like:

scope :yesterday, -> { where(created_at: 1.day.ago.all_day) }
like image 45
edymerchk Avatar answered Sep 27 '22 20:09

edymerchk