2013-02-11 43 views
0

情景:我想獲取與我的系統時間相關的最近時間。 我寫我的模型裏面下面的方法:postgresql時間和rails 3應用程序時間之間的差異

def self.nearest_class(day, teacher_id, hour_min) 
    day_of_week = '%' + day + '%' 
    if hour_min == "06:00:00" 
     where('frequency like ? AND teacher_id = ? AND (start_time >= ?)', day_of_week, teacher_id, hour_min).order('start_time ASC') 
    else 
     where('frequency like ? AND teacher_id = ? AND (start_time >= localtime(0))', day_of_week, teacher_id).order('start_time ASC') 
    end 
    end 

當我測試使用Lecture.nearest_class('Monday', 1, 'localtime(0)')在軌控制檯上面的方法,下面的查詢與一些數據一起返回:

SELECT "lectures".* FROM "lectures" WHERE (frequency like '%Monday%' AND teacher_id = 1 AND (start_time >= localtime(0))) ORDER BY start_time ASC 

但我由於我的系統時間大於數據庫中記錄的任何start_time,因此期待沒有記錄。我已經使用控制檯查詢pgadmin3來測試結果是否相同。但是,pgadmin3沒有顯示出預期結果。

postgresql時間和rails應用程序時間有差異嗎?我怎樣才能檢查這些差異?我在控制檯中嘗試了Time.now,它與pgadmin3中的SELECT LOCALTIME(0)相同。以最近的系統時間獲取記錄的正確方法是什麼?

爲了進一步設置上下文,這裏是我的控制器方法:

def showlectures 
    @teacher = Teacher.login(params[:id]).first 
    @lecture_by_course = nil 
    if @teacher 
     WEEKDAY.each do |day| 
      hour_min = "06:00:00" 
      if day == Time.now.strftime("%A") # check if day of week is same e.g. 'Monday' 
       hour_min = "localtime(0)" # system time with format: HH:MM:SS 
      end 
      @lecture_by_course = Lecture.nearest_class(day, @teacher.id, hour_min).first 
      if @lecture_by_course 
       break 
      end 
     end 
    end 

    render json: @lecture_by_course, include: { course: { only: [:name, :id] }} 
end 
+0

您的'start_time'字段是否定義爲有或沒有時區? PostgreSQL ['localtime(precision)'](http://www.postgresql.org/docs/9.2/static/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT)沒有時區,所以你可能有不匹配的時區比較期望。改用'current_time'。 – dbenhur 2013-02-11 03:18:07

+0

@dbenhur:Rails將使用沒有時區的時間戳,並強制數據庫中的所有內容都採用UTC。 – 2013-02-11 04:15:30

回答

1

我解決了這個被剛好路過服務器Time.now而不必一個SQL檢查。 {:| d'oh}