Ruby on rails 在rails sql语句中获取特定时区
在我的Rails应用程序中,我正在执行以下查询Ruby on rails 在rails sql语句中获取特定时区,ruby-on-rails,ruby,Ruby On Rails,Ruby,在我的Rails应用程序中,我正在执行以下查询 sql = "select A.bus_id as busid, A.stop_id as source, A.arrival as atime, B.arrival as dtime from (SELECT * from schedules as S where S.stop_id = #{startStopId}) A inner join (SELECT * from schedules as S where S.stop_id = #{e
sql = "select A.bus_id as busid, A.stop_id as source, A.arrival as atime, B.arrival as dtime from
(SELECT * from schedules as S where S.stop_id = #{startStopId}) A
inner join
(SELECT * from schedules as S where S.stop_id = #{endStopId}) B
on A.bustag = B.bustag
where A.arrival < B.arrival
and A.arrival > #{Time.now} "
我得到以下错误
ActiveRecord::StatementInvalid in WelcomeController#create
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '15:21:07 +0000' at line 7: select A.bus_id as busid, A.stop_id as source, A.arrival as atime, B.arrival as dtime from (SELECT * from schedules as S where S.stop_id = 25) A inner join (SELECT * from schedules as S where S.stop_id = 1) B on A.bustag = B.bustag where A.arrival < B.arrival and A.arrival > 2015-05-03 15:21:07 +0000
我基本上想做以下几点
到达>东部标准时间
我注意到的一件事是时间。现在似乎给了我UTC时间
所以我想到了这个解决方案
#subtract 4 hours to get eastern standard time from UTC.
@time_ = Time.now -0400
sql = "select A.bus_id as busid, A.stop_id as source, A.arrival as atime, B.arrival as dtime from
(SELECT * from schedules as S where S.stop_id = #{startStopId}) A
inner join
(SELECT * from schedules as S where S.stop_id = #{endStopId}) B
on A.bustag = B.bustag
where A.arrival < B.arrival
and A.arrival > #{@time_} "
我仍然得到一个错误。我不知道该怎么办了。感谢所有帮助。例如,您可以告诉rails为特定块使用特定时区
Time.use_zone('UTC') do
# your query
end
该块中的代码在其计算中使用该时区,而不是time.now使用time.zone.now
如果您想在整个时区应用程序范围内进行更改,请在application.rb中进行更改
如果您更改了应用程序,请不要忘记重新启动服务器和/或控制台。rb您必须在{Time.now}前后使用引号 例如:…A.arrival>“{Time.now}” 如果要将UTC更改为EST,可以执行以下操作:
Time.now.in_time_zone("EST").to_s
但这能解决我的错误吗,因为我认为Time.now默认使用UTC,那么为什么会出现这种错误呢?您是否也可以使用EST而不是UTC?我要东部标准时间我刚才用UTC作为占位符,你可以用你想要的任何时区,因此,是的,用ESTIts替换UTC不起作用,因为出于某种原因,我仍然会遇到相同的语法错误A.arrival>2015-05-03 15:21:07+0000这是它最终的格式,无法正确识别。是否将Time.now替换为Time.zone.now?仅当使用use_zone时,才需要进行替换,如果您使用了application.rb,那么您需要重新启动服务器/控制台不要在SQL字符串中使用{}插值-这会使您容易受到SQL注入攻击。哦,我没有注意到,谢谢提醒。你能给我一个解决m问题的方法吗?我想应该是a.arrival>{Time.now}@liuzxc这是我最初做的,但是出于某种原因,它也打印了日期,因此给了我无效的语法错误如果你想把UTC时间改成EST,你可以试试:a.arrival>{Time.now.in_Time_zoneEST.to_s}'sql=选择A.bus_id作为busid,A.stop_id作为源,A.arrival作为atime,B.arrival作为dtime从select*从schedules作为S其中S.stop_id={startStopId}从schedules作为S其中S.stop_id={endStopId}B on A.bustag=B.bustag其中A.arrival
Time.now.in_time_zone("EST").to_s