Last active
September 24, 2015 21:37
-
-
Save rafaelcgo/819f95712db833db5d55 to your computer and use it in GitHub Desktop.
Group_by with same attribute name or new attribute name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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]] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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]] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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