weird time_zone EDT vs EST issue with Rails - ruby-on-rails

I have a rails 5 server that is configured to be "Eastern Time (US & Canada)"
The server works great mostly, it stores times in the database in UTC.
For example, if I am in a console and do
Time.zone.now
=> Fri, 27 Oct 2017 15:07:04 EDT -04:00
Which is correct (we have not fall back on time yet)
However if I pull down an active record object:
> s = Schedule.first
Schedule Load (6.2ms) SELECT "schedules".* FROM "schedules" ORDER BY "schedules"."id" ASC LIMIT $1 [["LIMIT", 1]]
=> #<Schedule id: 1, product_id: 1, day: "Monday", start_time: "2000-01-01 22:00:00", end_time: "2000-01-01 23:00:00", size: 25, description: "Grades 3-5", created_at: "2017-08-23 14:16:09", updated_at: "2017-08-23 14:16:09", is_full: false>
2.4.0 :004 > s.start_time
=> Sat, 01 Jan 2000 17:00:00 EST -05:00
As you can see it convert is to Easter Standard time, which is not correct. Is it possible rails is confused or am I doing something wrong?
(using ruby 2.4)

This was user error, the objects date was in EST so Active Record was doing its job, fix was to set it to today and it would be in the right zone.

Related

Rails query where dates are greater than or less than two dates

I have a model where I am trying to come up with a query where I wanna select data if the starts_at is greater than today and the ends_at is less than today. The other caveat is checking if either one of those dates a NULL and if they aren't then the dates need to be checked against todays date also.
my_model.where("? >= starts_at AND ? <= ends_at OR (starts_at IS NULL OR ends_at IS NULL)", Ti
me.now.beginning_of_day, Time.now.end_of_day)
That code seems to pull back data sometimes and other times it doesn't.
** UPDATE **
Here are a few code examples
=> Menu Load (0.9ms) SELECT "menus".* FROM "menus" WHERE "menus"."account_id" = $1 AND ('2021-09-24 00:00:00' >= starts_at AND '2021-09-24 23:59:59.999999' <= ends_at OR (starts_at IS NULL OR ends_at IS NULL)) [["account_id", 1]]
[#<Menu:0x00005635d5657028
id: 4,
menu_type: "standard",
name: "Promo Menu",
starts_at: Fri, 24 Sep 2021 00:00:00.000000000 UTC +00:00,
ends_at: Fri, 01 Oct 2021 15:19:32.075844000 UTC +00:00,
never_ends: false,
account_id: 1,
created_at: Fri, 24 Sep 2021 00:37:44.127698000 UTC +00:00,
updated_at: Fri, 24 Sep 2021 16:03:06.558332000 UTC +00:00,
available: true>]
The above loads menus correctly, but heres a menu with a starts_at and ends_at within the query time frame and doesn't return
=> #<Menu:0x00005635d56d6e40
id: 1,
menu_type: "standard",
name: "Main Menu",
starts_at: Fri, 24 Sep 2021 00:37:43.512403000 UTC +00:00,
ends_at: Sat, 25 Sep 2021 17:46:13.450433000 UTC +00:00,
never_ends: false,
account_id: 1,
created_at: Fri, 24 Sep 2021 00:37:43.532613000 UTC +00:00,
updated_at: Fri, 24 Sep 2021 17:46:13.455113000 UTC +00:00,
available: true>
I think your query is correct. I guess you couldn't get the records sometimes because of the time zone. What's the timezone of the Rails app?

Rails refuses to add associated record

I have a table with 2 foreign key relationships - to a Timeline and a Phase. When I create a record in my development database it all works 100% as expected, but when I do it in test mode it refuses to add the Timeline - you can see from the INSERT statement that it flatly refuses .. it doesn't even try to add it. When I run the exact same sequence below in development it's fine
I can add/update timeline_id but then it doesn't reference the timeline through the parent phase_timeline object as it should. I repeat that this all works fine in development, but not in test. Its driving me mad. Is it failing a validation possibly.. or could the database be corrupt. Are there some console commands I could run to check out the foreign key relationship further?
[33] pry(main)> t = Timeline.last
Timeline Load (0.3ms) SELECT "timelines".* FROM "timelines" ORDER BY "timelines"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> #<Timeline:0x0055fd716dcfa8 id: 1, title: "England", timelineable_type: "Global", timelineable_id: 1, created_at: Thu, 24 Sep 2020 14:46:28 UTC +00:00, updated_at: Thu, 24 Sep 2020 14:46:28 UTC +00:00>
[34] pry(main)> p = Phase.last
Phase Load (1.3ms) SELECT "phases".* FROM "phases" WHERE "phases"."deleted_at" IS NULL ORDER BY "phases"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> #<Phase:0x0055fd717f8450
id: 1,
name: "First phase",
development_id: 1,
created_at: Thu, 24 Sep 2020 14:46:28 UTC +00:00,
updated_at: Thu, 24 Sep 2020 14:46:28 UTC +00:00,
developer_id: 1,
division_id: 1,
number: 1,
deleted_at: nil,
total_snags: 0,
unresolved_snags: 0,
business: "core">
[35] pry(main)> pt = PhaseTimeline.create(phase: p, timeline: t)
(0.2ms) BEGIN
SQL (0.5ms) **INSERT INTO "phase_timelines" ("phase_id") VALUES ($1) RETURNING "id" [["phase_id", 1]]**
(1.8ms) COMMIT
=> #<PhaseTimeline:0x0055fd719ef9c0 id: 5, phase_id: 1, timeline_id: nil>
After a LOT of head scratching and diving into the bowels .. this problem was caused by having 2 model classes with the same name. The classes were in 2 separate folder but had the same scope and were identical but removing the errant one sorted the problem

Time.new subtracting 6 hours AND tacking on CST -6 on Heroku?

I'm sure there's some conversion thing I'm looking over here.
On Heroku's console,
irb(main):052:0> Time.new(2014, 1, 21)
=> 2014-01-21 00:00:00 +0000
However, setting a column to that:
irb(main):042:0> PressRelease.first.update_attribute :published_on, Time.new(2014, 1, 21)
PressRelease Load (1.9ms) SELECT "press_releases".* FROM "press_releases" ORDER BY created_at DESC LIMIT 1
(1.0ms) BEGIN
FriendlyId::Slug Load (0.8ms) SELECT "friendly_id_slugs".* FROM "friendly_id_slugs" WHERE "friendly_id_slugs"."sluggable_id" = 1 AND "friendly_id_slugs"."sluggable_type" = 'PressRelease' ORDER BY "friendly_id_slugs".id DESC LIMIT 1
(0.6ms) COMMIT
=> true
Gives this date:
=> Mon, 20 Jan 2014 18:00:00 CST -06:00
To clarify, application.rb does indeed have the time zone set:
config.time_zone = 'Central Time (US & Canada)'
And when I check on their console:
irb(main):054:0> Time.zone
=> (GMT-06:00) Central Time (US & Canada)
However, doing this locally works fine:
1.9.3-p448 :011 > Time.new(2014, 1, 21)
=> 2014-01-21 00:00:00 -0600
So, it looks like Heroku is subtracting -6 (since our Time Zone is set to CST -6), then tacking on the timezone of CST -6 as well. Why? This is, as you can see, messing up date-specific items.
If you want Rails to use the time_zone setting, you need to use the wrappers provided by ActiveSupport::TimeZone. See docs: http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html
Here's an example:
Time.zone.parse("2014-1-21")
# Outputs Tue, 21 Jan 2014 00:00:00 MST -07:00

Rails: Clarification (rules-of-thumb?) for Date/Time, to_time and time zones

tl;dr: what are the rules for working with Date, Time & Datetime so I'm assured consistency across my apps?
I'm trying to wrap my head around working with Dates & Times & Zones in Rails so I don't accidentally use UTC when I really want all "user facing" dates/times adjusted for time zone. I'm noticing what appears, to me at least, to be some inconsistency and I'm hoping to understand rules or logic behind them so I'm not "surprised" again.
1.9.3p194 :028 > e = Event.find(1)
Event Load (0.3ms) SELECT "events".* FROM "events" WHERE "events"."id" = $1 LIMIT 1 [["id", 1]]
=> #<Event id: 1, start_at: "2012-08-27 19:15:00", end_at: "2012-08-27 21:00:00", created_at: "2012-08-22 07:43:31", updated_at: "2012-08-23 03:01:59">
1.9.3p194 :037 > e.start_at # <== start_at is DateTime in model
=> Mon, 27 Aug 2012 12:15:00 PDT -07:00
1.9.3p194 :036 > e.start_at.to_time
=> 2012-08-27 19:15:00 UTC ### <=== This is in UTC.. ok...
1.9.3p194 :034 > DateTime.now
=> Thu, 23 Aug 2012 10:44:16 -0700 # <=== Also a DateTime
1.9.3p194 :035 > DateTime.now.to_time
=> Thu, 23 Aug 2012 10:44:19 -0700 ### <=== But this is in Pacific Time ?!?
2 differing responses from to_time? Or did I miss something?
The fairly cryptic documentation for DateTime's to_time doesn't make any mention of timezone:
to_time()
Attempts to convert self to a Ruby Time object; returns self if out of range of Ruby Time class. If self has an offset other than 0, self will just be returned unaltered, since there’s no clean way to map it to a Time.
So what are "rules" for getting consistent dates & times out of Rails?
I'm assuming you have a start_at column in your database. As a result e.start_at is not an instance of DateTime but an instance of Time. (Try calling e.start_at.class to see it)
Instead of using DateTime.now I'd recommend using Rails' Time.zone.now which will return the current time in the timezone defined in Time.zone.
1.9.3p125 :005 > Time.zone
=> (GMT+00:00) UTC
1.9.3p125 :006 > Time.zone.now
=> Thu, 23 Aug 2012 20:10:34 UTC +00:00
1.9.3p125 :007 > Time.zone = "Berlin"
=> "Berlin"
1.9.3p125 :008 > Time.zone
=> (GMT+01:00) Berlin
1.9.3p125 :009 > Time.zone.now
=> Thu, 23 Aug 2012 22:10:47 CEST +02:00

Rails config.time_zone and datetime attribute update

In my application I have: config.time_zone = 'Warsaw'
A strange issue I have, is that it seems like Rails are having problems with comparision of datetime fields.
If I change the datetime 1 hour back (and Warsaw is currently in timezone +0100), Rails won't update the database, even if the field has changed. However, if I change the field once again, then the update will go to the database.
Example:
(Rails 3.1.0, ruby-1.9.2-p290, fresh rails app):
$ rails g model User starts_at:datetime
$ rake db:migrate
$ rails c
Loading development environment (Rails 3.1.0)
ruby-1.9.2-p290 :001 > u = User.create({:starts_at => "2011-01-01 10:00"})
SQL (21.3ms) INSERT INTO "users" ("created_at", "starts_at", "updated_at") VALUES (?, ?, ?) [["created_at", Tue, 13 Dec 2011 11:32:50 CET +01:00], ["starts_at", Sat, 01 Jan 2011 10:00:00 CET +01:00], ["updated_at", Tue, 13 Dec 2011 11:32:50 CET +01:00]]
=> #<User id: 1, starts_at: "2011-01-01 09:00:00", created_at: "2011-12-13 10:32:50", updated_at: "2011-12-13 10:32:50">
ruby-1.9.2-p290 :002 > u.starts_at
=> Sat, 01 Jan 2011 10:00:00 CET +01:00 # datetime created
ruby-1.9.2-p290 :003 > u.starts_at = "2011-01-01 09:00:00" # new datetime with one hour back
=> "2011-01-01 09:00:00"
ruby-1.9.2-p290 :004 > u.starts_at
=> Sat, 01 Jan 2011 09:00:00 CET +01:00 # changed datetime
ruby-1.9.2-p290 :005 > u.save
=> true
ruby-1.9.2-p290 :006 > u.starts_at = "2011-01-01 09:00:00"
=> "2011-01-01 09:00:00"
ruby-1.9.2-p290 :007 > u.save
(0.3ms) UPDATE "users" SET "starts_at" = '2011-01-01 08:00:00.000000', "updated_at" = '2011-12-13 10:33:17.919092' WHERE "users"."id" = 1
=> true
I've tested it in this fresh app, because I have a problem with this in larger application. What is going on? I've tried to browse the Rails code, tried to re-copy the relevant code 'by-hand' in console (like update, assign_attributes, even checked time_zone_conversion) and it worked, but not in 'real world'..
looks like you stumbled on a similar issue.
The problem appears to be here:
https://github.com/rails/rails/blob/3-1-stable/activerecord/lib/active_record/attribute_methods/dirty.rb#L62
When rails it testing if the value was changed it compares old & new:
old = From cache (which is Time in your current timezone)
new = Time in UTC (+00:00) as saved in the database
If the difference in time is the UTC offset, the above erroneously succeeds (luckly the new cached value holds the intended change).
The next save/update compares with the new (and correct) cached value and marks the field as changed.
EDIT:
Done some tests, this works well for me:
https://github.com/rails/rails/blob/3-1-stable/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb#L50
Change
write_attribute(:#{attr_name}, original_time)
to
write_attribute(:#{attr_name}, time.in_time_zone('UTC').to_s)
Boris

Resources