How can I find records from today, yesterday and so on with Ruby on Rails?

匆匆过客 提交于 2019-12-23 14:11:09

问题


I want to find all records, say Posts, created today with Ruby on Rails, then all Posts created yesterday, and so on… how should I do?

Thank you,

Kevin


回答1:


Try this:

#Today
Posts.find(:all, conditions: { :created_at => Date.today...Date.today + 1 })
#Yesterday
Posts.find(:all, conditions: { :created_at => Date.today - 1...Date.today })

Or this (preferable, in my opinion):

#Today
Posts.find(:all, conditions: ["DATE(created_at) = ?", Date.today] )
#Yesterday
Posts.find(:all, conditions: ["DATE(created_at) = ?", Date.today - 1] )



回答2:


As a rule I store all dates on my server in UTC timezone and let the UI handle any timezone conversion. To get the sort of query you are after to work correctly I had to massage the incoming date into a UTC specific time range first.

require 'date'

class Post < ActiveRecord::Base

  def self.created(a_date)
    return Post.where(created_at: to_timerange(a_date))
  end

  private

  def self.to_timerange(a_date)
    raise ArgumentError, "expected 'a_date' to be a Date" unless a_date.is_a? Date
    dts = Time.new(a_date.year, a_date.month, a_date.day, 0, 0, 0).utc
    dte = dts + (24 * 60 * 60) - 1
    return (dts...dte)
  end

end

This then allows you to call

# today
posts = Post.created(Date.today)
# yesterday
posts = Post.created(Date.today - 1)


来源:https://stackoverflow.com/questions/3570740/how-can-i-find-records-from-today-yesterday-and-so-on-with-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!