1. 程式人生 > 其它 >Ruby on Rails 日期查詢和修改的方法--資料庫常用操作

Ruby on Rails 日期查詢和修改的方法--資料庫常用操作

Ruby on Rails 日期查詢方法

查詢近超過1個小時的數量

Order.where(' created_at <= ? ', DateTime.now - 1.hours).count

查詢近三個月的數量

Order.where(' created_at >= ? ', DateTime.now - 3.month).count

查詢上個月的數量

Order.where(created_at: (DateTime.now - 1.month).beginning_of_month..DateTime.now.beginning_of_month).count

查詢本月的數量

Order.where(' created_at >= ? ', DateTime.now.beginning_of_month).count

近一週

Order.where(' created_at >= ? ', DateTime.now - 7.day).count

修改超過一個小時的資料

    # 修改超過一個小時的任務
    # past_time = (n_time - 1.hours).strftime("%Y-%m-%d %H:%M:%S") 
    # => "2021-08-05 20:55:31" 
    CategoryStatistic
      .where("state = 'init' and end_at IS NULL ")
      .where("begin_at<=?", DateTime.now - 1.hours)
      .update_all(state: FAILED, end_at: n_time, updated_at: n_time)

執行結果:

 UPDATE `category_statistics` SET `category_statistics`.`state` = 'failed', `category_statistics`.`end_at` = '2021-08-05 22:27:45', `category_statistics`.`updated_at` = '2021-08-05 22:27:45' WHERE (state = 'init' and end_at IS NULL ) AND (begin_at<='2021-08-05 21:27:45.684015')

批量修改

Client.where(id: init_ip_infos.pluck(:id)).update_all(state: "init")

[Haima的部落格] http://www.cnblogs.com/haima/