Tricky Active Record搜索。在凌晨3点到一天开始之间创建的记录

问题描述 投票:0回答:1

我有一个应用程序来跟踪与全球变暖有关的温度。

我有一个记录温度的PG数据库,然后尝试比较在Beginning_of_day直到凌晨3点或Beginning_of_day + 180创建的记录。

@@ today_records = Temp.where(Time.zone.now.beginning_of_day..Time.zone.now.beginning_of_day + 180)完美地工作。但是,我需要这些记录的日期不是Date.current或Time.zone.now或Time.zone.yesterday。这些时间必须是记录的发生日期,恰好存储在created_at和表的date:列中。

我尝试过类似@temps = Temp.all然后@ temps.where(“ created_at <= beginnig_of_day + 180 AND created_at> Beginning_of_day”)。如果我可以正确地获得语法和/或顺序/位置,则类似此伪代码的代码将起作用。

表中有date,temp_high列,我试图在很早的时候创建记录。我知道,如果该记录恰好是在begin_of_day创建的,则该Temp的实例(例如@ temp.created_at.beginning_of_day + 180)将是凌晨3点。

如何使用此搜索?

我的模型是城市和临时城市,其中城市有很多临时城市,临时城市属于一个城市

class City < ApplicationRecord 
    has_many :temps
end 

class Temp < ApplicationRecord
  belongs_to :city
end 

create_table "temps", force: :cascade do |t|
    t.datetime "date"
    t.integer "temp_high"
    t.integer "temp_mid"
    t.integer "temp_low"
    t.bigint "city_id", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.integer "sunset"
    t.index ["city_id"], name: "index_temps_on_city_id"
  end 
#routes.rb
get "/cities/temps/diff.json", to: 'temps#diff' 
#temps_controller 
 def diff 

      @cities = City.all 
      @temps = @cities.map{ |city| city.temps }  

      @hot = @temps.map{ |temp|  temp.map{ |city_temp| city_temp.try(:temp_high) } }   
      @cool = @temps.map{ |temp| temp.order(created_at: :desc).limit(3) } 
      render json: {HOTTEST: @hot, COOLEST: @cool }
    end 

update上面的回答实际上是一个很好的答案。在应用程序中,我得到的正是我想要的:在0000和凌晨3点之间创建的记录。 HOWEVERpostgresql使用utc,并将记录存储在utc时区中。它将记录留在服务器上,就好像它们是在实际创建5小时后创建的一样。

问题是Rails在后台做了很多事情,当您询问创建记录的记录时,会将其转换为设置的时区。即<Temp id: 5, date: "2020-03-28 09:04:23", temp_high: 42, temp_mid: 35, temp_low: 28, city_id: 3, created_at: "2020-03-28 09:04:24", updated_at: "2020-03-28 09:04:24", sunset: 1585436723, current_temp: 35, sunset_datetime: "2020-03-28 23:05:23">

如您所见,这个温度是“ created_at” 2020-03-28:09:04:23“

#<ActiveRecord::Relation [#<Temp id: 5, date: "2020-03-28 09:04:23", temp_high: 42, temp_mid: 35, temp_low: 28, city_id: 3, created_at: "2020-03-28 09:04:24", updated_at: "2020-03-28 09:04:24", sunset: 1585436723, current_temp: 35, sunset_datetime: "2020-03-28 23:05:23">]> 2.6.1 :007 > x[0].created_at Temp Load (0.8ms) SELECT "temps".* FROM "temps" WHERE "temps"."id" = $1 [["id", 5]] => Sat, 28 Mar 2020 02:04:24 MST -07:00

当直接使用记录并将其从数据库中拉出并询问它是何时创建的时,它会为您提供正确的时间02:04:24

我必须在postgresql中设置时区。 Postgesql正在使用UTC,一旦从数据库中提取出来,rails就会对其进行转换。

现在,我的问题是设置postgresql的时区。这是另一个问题,我只是将其发布给其他人学习。找到答案后,我将其发布。

activerecord ruby-on-rails-6 postgresql-10
1个回答
0
投票

我认为这可能行得通。

Temp.where("created_at BETWEEN 
            date_trunc('day', created_at) + interval '1 day' - interval '24 hour' AND 
            date_trunc('day', created_at) + interval '1 day' - interval '21 hour' ")

如果两者之间不适合您,则可以使用>=<运算符。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.