简体   繁体   中英

How do I group these objects into a hash?

I have an event modal, which has a datetime field titled scheduled_time . I need to create a hash that has a day name in a certain format ('mon', 'tue' etc) as the key, and the count of events that take place on that day as the value. How can I do this?

{
    'mon' => 2,
    'tue' => 4,
    'wed' => 3,
    'thu' => 5,
    'fri' => 12,
    'sat' => 11,
    'sun' => 7,
}

I'm using Rails 3.2.0 and Ruby 1.9.2

The easiest would be to use count with a :group option:

h = Model.count(:group => %q{to_char(scheduled_time, 'dy')})

The specific function that you'd GROUP BY would, as usual, depend on the database; the to_char approach above would work with PostgreSQL, with MySQL you could use date_format and lower :

h = Model.count(:group => %q{lower(date_format(scheduled_time, '%a'))})

For SQLite you'd probably use strftime with a %w format and then convert the numbers to strings by hand.

Note that using Model.count(:group => ...) will give you a Hash with holes in it: if there aren't any entries in the table for that day then the Hash won't have a key for it. If you really want seven keys all the time then create a Hash with zeros:

h = { 'mon' => 0, 'tue' => 0, ... }

and then merge the count results into it:

h.merge!(Model.count(:group => ...))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM