简体   繁体   中英

Get an array of hashes corresponding to the selected values with ActiveRecord

I have a sql database that I query with ActiveRecord. (version of ActiveRecord is 4.2.5.1)

My query look like this:

User.
  select('COUNT (DISTINCT user_id) as user_count').
  select("date_trunc('month', created_at) as month").
  select('city').
  where('created_at > ?', 1.year.ago.utc.to_s(:db)).
  group('month, city').
  to_a.map do |row|
  {
    user_count: row.user_count,
    month: row.month,
    city: row.city
  }

And I get results like this:

[
    [  0] {
        :user_count => 165,
             :month => 2015-09-01 00:00:00 UTC,
              :city => "Paris"
    },
    [  1] {
        :user_count => 33,
             :month => 2015-09-01 00:00:00 UTC,
              :city => "Berlin"
    },
    ...
]

And this is fine.

However, with this query:

User.
  select('COUNT (DISTINCT user_id) as user_count').
  select("date_trunc('month', created_at) as month").
  select('city').
  where('created_at > ?', 1.year.ago.utc.to_s(:db)).
  group('month, city').
  to_a

I get results like this:

[
    [  0] #<User:0x007facebac3560> {
           :user_id => nil,    # wtf is this
              :city => "Paris"
                               # where is the month?
    },
    [  1] #<User:0x007facebac33a8> {
           :user_id => nil,
              :city => "Berlin"
    },
    ...
]

Which is not fine.

Why do I have to manually map the results even when I selected the rows I wanted?

Ideally, what I want is this:

User.
  select(...).
  where(...).
  group(...).
  to_array_of_hashes_with_the_keys_i_selected

Notice that if my query is a custom query, to_a does what I want, for example:

ActiveRecord::Base.connection.execute(<<~SQL
  SELECT COUNT (DISTINCT user_id) as user_count, date_trunc('month', created_at) as month,  city
  FROM users
  WHERE created_at > '2015-09-01 13:28:40'
  GROUP BY month, city
SQL
).to_a # this is fine

From How to convert activerecord results into a array of hashes , I can do:

User.
  select(...).
  where(...).
  group(...).
  as_json

And I get

[
    [  0] {
           "user_id" => nil,
              "city" => "Paris",
        "user_count" => 165,
             "month" => 2015-09-01 00:00:00 UTC
    },
    ...

Not exactly what I selected, but close enough.

.as_json.map{|e|e.except('user_id')} gives me what I want

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