Skip to content

Instantly share code, notes, and snippets.

@matsubo
Forked from leods92/group_date.rb
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matsubo/22bf57ff33746b03a6a7 to your computer and use it in GitHub Desktop.
Save matsubo/22bf57ff33746b03a6a7 to your computer and use it in GitHub Desktop.
MySQL ONLY. Confirmed on Rails 4.0.x, MySQL 5.6.x
module ActiveRecord
module Querying
delegate :group_date, :to => :scoped
end
module QueryMethods
def group_date(column_name = nil)
return self if column_name.blank?
# Rails uses a non standard time zone naming.
# Let's get tz database standard which is used by many databases.
# Using this instead of time offset or other approaches is necessary
# in order to deal with daylight saving time automatically.
zone = Time.zone.now.strftime('%z').insert(3, ':')
# Rails stores timestamps without time zones by default.
# So we must first set a zone to column_name (column_name at time zone 'UTC').
# Note that even though Rails does that under the hood when you use ActiveRecord,
# that's not applicable here.
# Then, we set column to application's time zone so that the database can
# convert timestamp to proper date.
date = "date(CONVERT_TZ(#{table.name}.#{column_name}, '+00:00', \'#{zone}\'))"
# Since converting date is not that straight-forward,
# this will automatically return converted date.
# We gotta convert output date to assure Rails won't convert it again.
clone.group(date).select("#{date} as date_#{column_name}")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment