Skip to content

Instantly share code, notes, and snippets.

@rafaelcgo
Last active September 24, 2015 21:37
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 rafaelcgo/819f95712db833db5d55 to your computer and use it in GitHub Desktop.
Save rafaelcgo/819f95712db833db5d55 to your computer and use it in GitHub Desktop.
Group_by with same attribute name or new attribute name
date_start = Time.parse('11/08/2015').beginning_of_day
date_end = Time.parse('11/08/2015').end_of_day
created_at_day_tz = "date(created_at AT TIME ZONE \'UTC\'
AT TIME ZONE \'#{Time.zone.tzinfo.identifier}\')"
users = User.where("users.created_at BETWEEN ? AND ?", date_start, date_end)
# Grouping by created_at as created_at_day (date only, new name for the groupped attribute)
grouped_with_timezone_day = users.group(created_at_day_tz).
order(created_at_day_tz).
select("#{created_at_day_tz} as created_at_day, count(*) as count")
# grouped_with_timezone_day.map {|u| [u.created_at_day, u.count] }
# => [[Tue, 11 Aug 2015, 186]]
# Grouping by created_at as created_at (date only, same name for the groupped attribute)
grouped_with_timezone = users.group(created_at_day_tz).
order(created_at_day_tz).
select("#{created_at_day_tz} as created_at, count(*) as count")
# grouped_with_timezone.map {|u| [u.created_at, u.count] }
# => [[Mon, 10 Aug 2015 21:00:00 BRT -03:00, 186]]
How come the days are different on the results of example 2_ and example 3_ ?
The only difference is the groupped attribute name.
If I do I18n.l(user.created_at) on the results I will have wrong dates.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment