【问题标题】:Compare a date in rails Active Record and PG比较 Rails Active Record 和 PG 中的日期
【发布时间】:2017-06-25 17:50:48
【问题描述】:

我正在尝试返回前天的记录。我的记录有 date created_at 列,其中包含日期和时间。而我的条件只有日期,所以它总是不返回任何记录。

我让它在 sqlite 上的 dev 上工作,使用 strftime 来删除时间,但是我该如何在 PG 上进行直播?

@articles = Article.where("created_at = ?", Date.yesterday-(params[:increment].to_i)).reverse

(增量 = 前天的天数。)

非常感谢

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    在当前版本的 Rails(自 5.1 版起)中,您可以使用 all_day helper 进行这样的查询:

    date = (params[:increment].to_i + 1).days.ago
    Article.where(created_at: date.all_day).reverse
    

    【讨论】:

      【解决方案2】:

      几种方法。虽然我更喜欢这样的日期范围:

      .where("created_at > ? AND created_at < ?", date_from, date_to)
      

      你也可以使用PostgreSQL内置的date_trunc函数

      .where("date_trunc('day', created_at) = ?", date)
      

      但请记住,您的本地开发机器上也需要 postgres。

      文档:https://www.postgresql.org/docs/9.1/static/functions-datetime.html

      【讨论】:

        【解决方案3】:

        说今天是

        > DateTime.now
         => Mon, 26 Jun 2017 00:17:12 +0545
        

        > Account.where('created_at between ? and ?', 2.days.ago.beginning_of_day, 2.days.ago.end_of_day)
          Account Load (0.5ms)  SELECT  "accounts".* FROM "accounts" WHERE (created_at between '2017-06-23 00:00:00' and '2017-06-23 23:59:59.999999') LIMIT ?  [["LIMIT", 11]]
        
        
         => #<ActiveRecord::Relation [#<Asset id: 3, name: "created 4 days ago", code: nil, type: "Asset", created_at: "2017-06-17 06:57:13", updated_at: "2017-06-21 06:57:13">]> 
        
        • 这样,你会发现从Jun 25 00:00:00开头到Jun 26 00:00:00的文章。

        了解beginning_of_dayend_of_day

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-20
          • 1970-01-01
          • 2014-03-12
          • 1970-01-01
          相关资源
          最近更新 更多