场景:我想获得与我的系统时间相关的最近时间。我在我的模型中编写了以下方法:
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
当我在 rails 控制台中使用 测试上述方法时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