Ruby on rails 3 postgresql时间和rails 3应用程序时间之间的差异
场景:我想获得与系统时间最接近的时间。 我在模型中编写了以下方法:Ruby on rails 3 postgresql时间和rails 3应用程序时间之间的差异,ruby-on-rails-3,postgresql,Ruby On Rails 3,Postgresql,场景:我想获得与系统时间最接近的时间。 我在模型中编写了以下方法: 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,
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控制台中使用teaching.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
但我不希望有任何记录,因为我的系统时间大于数据库中记录的任何开始时间。我使用了从控制台到pgadmin3的查询来测试结果是否相同。然而,pgadmin3没有显示出预期的结果
postgresql时间和rails应用程序时间有区别吗?我怎样才能检查这些差异?我尝试了Time。现在在控制台中,它与从pgadmin3中选择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
我只是通过传递服务器时间来解决了这个问题。现在不再进行SQL检查。{:|d'oh}您的开始时间
字段定义为带时区还是不带时区?PostgreSQL没有时区,因此在比较中可能会出现不匹配的时区预期。改为尝试current\u time
。@dbenhur:Rails将使用不带时区的时间戳,并强制数据库中的所有内容都使用UTC。