Rails ActiveRecord where datetime not working - ruby-on-rails

I have a Model which has_one Schedule (from:datetime, from_a:datetime, to:datetime). I want to retrieve all models that have a schedule that fits the datetime the query is run.
For example, I have the model m that has a schedule of from: Sun, 15 Oct 2018 19:00:00 UTC +00:00, from_a: Sun, 14 Oct 2018 19:20:00 UTC +00:00 and to: Sun, 14 Oct 2018 20:00:00 UTC +00:00. If the current time is Sun, 14 Oct 2018 19:14:00 UTC +00:00 then and I search with only from then I would get m, but if the current time is Sun, 14 Oct 2018 20:01:00 UTC +00:00 and I search with only from I would get nothing.
Here is the code that I've tried:
scope :s, ->(time, type) { unscoped.joins(:schedule).where("\"schedule.#{type.to_s}\" < ? AND \"schedule.to\" > ?", time, time) }
and when I call the scope would be Model.s(DateTime.now, :from). The thing is that this code is not working as intended as it doesn't give me the correct result, nor the result that I expect.
UPDATE
This is the generated query for Model.s(DateTime.now, :from)
SELECT "models".* FROM "models" INNER JOIN "schedules" ON "schedules"."model_id" = "models"."id" WHERE ("schedules.from" < '2018-10-15 19:59:33.737073' AND "schedules.to" > '2018-10-15 19:59:33.737073')

You have several problems, the first of which hides the others:
Single quotes are used for string literals in SQL so 'schedule.from' and 'schedule.to' are just strings in SQL, not references to columns in the schedule table.
schedule should be schedules since Rails likes to use plurals for table names.
to and from are keywords in SQL and PostgreSQL (which you appear to be using) so they have to be (double) quoted when you use them as column names.
The first is fixed by removing the stray single quotes. The second by using a plural table name. The third by double quoting the offending identifiers. The result would be something like:
unscoped.joins(:schedule).where(%Q(schedules."#{type.to_s}" < ? and schedules."to" > ?), time, time)
or perhaps:
unscoped.joins(:schedule).where(%Q(schedules."#{type.to_s}" < :time and schedules."to" > :time), time: time)

Related

comparing current time to UTC

I'm trying to query the DB for the opening time of a store.
The open_at when queried from the DB returns:
2000-01-01 16:18:00 +0000
When I run Time.current it returns
Tue, 14 Jun 2016 16:32:46 CEST +02:00
Now I'm trying to do:
store.business_hours.where('open_at <= ?', Time.current)
it returns an empty ActiveRecord array as such:
#<ActiveRecord::AssociationRelation []>
now what I'm trying to do is make it so that the open_at in-fact shows, and that it's able to understand the time zone difference.

Rails query find result with partiular day with where cluase

I want to orders which are confirmed particular day.
This is particular day:
today = Time.zone.now
Wed, 10 Jun 2015 13:31:16 IST +05:30
This is range of particular day
value = today.beginning_of_day()..today.end_of_day()
Wed, 10 Jun 2015 00:00:00 IST +05:30..Wed, 10 Jun 2015 23:59:59 IST +05:30
But when I execute this, SQL query date range is changed,
orders = Order.where(confirmed_at: value)
SELECT "orders".* FROM "orders" WHERE "orders"."confirmed_at" BETWEEN '2015-06-09 18:30:00.000000' AND '2015-06-10 18:29:59.999999' ORDER BY orders.confirmed_at DESC
In this orders confiremed between '2015-06-09 18:30:00.000000' AND '2015-06-10 18:29:59.999999'
But I wants confirmed between 'Wed, 10 Jun 2015 00:00:00 IST +05:30..Wed, 10 Jun 2015 23:59:59 IST +05:30'
You can use Time.zone.now.to_time for today.
today = Time.zone.now.to_time
value = today.beginning_of_day()..today.end_of_day()
I hope this helps.
Which DB are you using?
ActiveRecord will declare time columns using data types that do not support timezones. For example, in Postgres it will use timestamp without time zone.
This means that all Time, DateTime and TimeWithZone values set on an ActiveRecord object will be written to the DB as UTC.
Rails will then take care to apply and remove the right offsets each time the values are read or written, using the current value of Time.zone (e.g. for the current web request).
Just check the docs for TimeWithZone and think about what should go in your WHERE clause.
It probably depends on the specific context, but you might have to use UTC values in your query.

Rails Records with times in different timestamps that occur on a date

Rails 4.2 and PostgreSQL 9.4.
I have events with starts_at and time_zone columns.
I'd like a SQL query to return all events that start, in their local time zone, on a specified date.
I.e. if an event starts at 11pm in Hawaii on Jan 24th:
t1 = ActiveSupport::TimeZone['Hawaii'].parse("2015-01-24 23:00:00")
=> Sat, 24 Jan 2015 23:00:00 HST -10:00
t1.in_time_zone('UTC')
=> Sun, 25 Jan 2015 09:00:00 UTC +00:00
And if an event starts at 1am in Hong Kong on Jan 24th:
t2 = ActiveSupport::TimeZone['Hong Kong'].parse("2015-01-24 01:00:00")
=> Sat, 24 Jan 2015 01:00:00 HKT +08:00
t2.in_time_zone('UTC')
=> Fri, 23 Jan 2015 17:00:00 UTC +00:00
The events occur on the 25th and 23rd of Jan in Rails' implicit UTC database zone, but both events occur on the 24th in their own time zone.
I'd like to write a SQL query akin to:
SELECT * FROM events WHERE (events.starts_at at time zone 'UTC' at time zone events.time_zone)::date = '2015-01-24';
(The initial conversion to UTC is required for a timestamp I believe)
However I get an error ERROR: time zone "Hawaii" not recognized
This is because PostgreSQL time zone names do not match with that of Rails (SELECT * FROM pg_timezone_names; for a list.)
Is there an alternative method where I can still do the query in SQL but not have this problem? I don't want to load the entire events set into Rails and process it there as it is very large and this is a frequent query.
As a small context as to why I need this query: I have a membership pass valid over a certain date range which gives you access to events which can occur in different time zones.
If there is no other way to do this, is there any tool that converts between the Rails names for time zones and that used by PostgreSQL so that I can save both the Rails zone and the PostgreSQL zone in the database record?
Using time zone abbreviations such as PDT instead (I don't even know if these are consistent between Rails and PostgreSQL either) doesn't deal with daylight savings time (which, granted, may not be an issue here but is not satisfactory).

In the context of rails, how can I order columns by the second?

I am working with rails and postgresql. I have a created_at timestamp on a model. I am in a situation where I need to order the results by second. I can't seem to get rails todo this.
e.g. If I insert 5 records in 1 minute, and then want to sort by created_at time, since they all have the same minute, it starts to order them by alpha because they all have the same insert minute.
How can I make it so that it orders by the insert in seconds. Postgres is storing it. But DateTime doesn't seem to take seconds into account in this way...
I hope this makes sense
Kirk
ActiveRecord order method should sort including the second
Eg:
Note the last two datetimes are in the same minute
User.pluck(:created_at)
=> [Fri, 14 Mar 2014 16:26:02 UTC +00:00, Fri, 14 Mar 2014 18:33:42 UTC +00:00, Fri, 14 Mar 2014 18:33:51 UTC +00:00]
User.order("created_at desc").collect(&:created_at)
=> [Fri, 14 Mar 2014 18:33:51 UTC +00:00, Fri, 14 Mar 2014 18:33:42 UTC +00:00, Fri, 14 Mar 2014 16:26:02 UTC +00:00]
Adding:
default_scope -> { order('created_at DESC') }
to your ActiveRecord should do it because created_at should look like this:"2014-03-12 15:29:26" which specifies the seconds.

Why does this rails query behave differently depending on timezone?

I have a rails time-based query which has some odd timezone sensitive behaviour, even though as far as I know I'm using UTC. In a nutshell, these queries give different answers:
>> Model.find(:all,:conditions=>['created_at<=?',(Time.now-1.hours).gmtime]).length
=> 279
>> Model.find(:all,:conditions=>['created_at<=?',(Time.now-1.hours)]).length
=> 280
Where the DB actually does contain one model created in the last hour, and the total number of models is 280. So only the first query is correct.
However, in environment.rb I have:
config.time_zone = 'UTC'
The system time zone (as reported by 'date') is BST (which is GMT+1) - so somehow this winds up getting treated as UTC and breaking queries.
This is causing me all sorts of problems as I need to parameterise the query passing in different times to an action (which are then converted using Time.parse()), and even though I send in UTC times, this 'off by one hour' DST issue crops a lot. Even using '.gmtime()' doesn't always seem to fix it.
Obviously the difference is caused somehow by an implicit conversion somewhere resulting in BST being incorrectly treated as UTC, but why? Doesn't rails store the timestamps in UTC? Isn't the Time class timezone aware? I am using Rails 2.2.2
So what is going on here - and what is the safe way to program around it?
edit, some additional info to show what the DB and Time class are doing:
>> Model.find(:last).created_at
=> Tue, 11 Aug 2009 20:31:07 UTC +00:00
>> Time.now
=> Tue Aug 11 22:00:18 +0100 2009
>> Time.now.gmtime
=> Tue Aug 11 21:00:22 UTC 2009
The Time class isn't directly aware of your configured timezone. Rails 2.1 added a bunch of timezone support, but Time will still act upon your local timezone. This is why Time.now returns a BST time.
What you likely want is to interact with Time.zone. You can call methods on this like you would the Time class itself but it will return it in the specified time zone.
Time.zone.now # => Tue, 11 Aug 2009 21:31:45 UTC +00:00
Time.zone.parse("2:30 PM Aug 23, 2009") # => Sun, 23 Aug 2009 14:30:00 UTC +00:00
Another thing you have to be careful with is if you ever do queries on the database where you are comparing times, but sure to use the UTC time (even if you have a different time zone specified) because Rails always stores UTC in the database.
Item.all(:conditions => ["published_at <= ?", Time.now.utc])
Also, instead of Time.now-1.hour do 1.hour.ago. It is easier to read and Rails will automatically use the configured timezone.
The TimeZone you need to set is UK, this will automatically handle BST
Time.zone = 'UK'
Time.zone.now
=> Sun, 17 Oct 2010 02:09:54 BST +01:00
start_date_format = DateTime.strptime(#start_date, date_format)
start_date_format_with_hour =
DateTime.strptime((start_date_format.to_i + timezone_offset*60*60).to_s,'%s').strftime(date_format)
end_date_format = DateTime.strptime(#end_date, date_format)
end_date_format_with_hour = DateTime.strptime((end_date_format.to_i + timezone_offset*60*60).to_s,'%s').strftime(date_format)
#filters_date = "invoices.created_at >= ? AND invoices.created_at < ?", start_date_format_with_hour, end_date_format_with_hour

Resources