簡體   English   中英

使用ActiveRecord獲取與所選值對應的哈希數組

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

我有一個用ActiveRecord查詢的SQL數據庫。 (ActiveRecord的版本為4.2.5.1)

我的查詢如下所示:

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
  }

我得到這樣的結果:

[
    [  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"
    },
    ...
]

這很好。

但是,使用此查詢:

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

我得到這樣的結果:

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

哪個不好

為什么即使選擇了想要的行也必須手動映射結果?

理想情況下,我想要的是:

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

請注意,如果我的查詢是自定義查詢,則to_a會執行我想要的操作,例如:

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

如何將activerecord結果轉換為哈希數組 ,我可以做到:

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

我得到

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

不完全是我選擇的,但足夠接近。

.as_json.map{|e|e.except('user_id')}給了我我想要的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM