简体   繁体   English

ActiveRecord 组不返回带有值对象数组的哈希值

[英]ActiveRecord group not returning hash with arrays of objects for values

I know this has been asked and answered a lot.我知道这已经被问到并回答了很多。 I have two tables Foo and Bar.我有两张桌子 Foo 和 Bar。

class Foo < ApplicationRecord
  belongs_to :bar
  ...

Foo has attributes of id and name and bar_id Foo 具有idnamebar_id属性

and

class Bar < ApplicationRecord
  has_many :foos
  ...

Bar has the attributes, id and name . Bar 具有属性idname

When I simply try Foo.group(:bar_id) I get #<Foo::ActiveRecord_Relation:0x3fdeac1cc274>当我简单地尝试Foo.group(:bar_id)我得到#<Foo::ActiveRecord_Relation:0x3fdeac1cc274>

With Foo.group(:bar_id).count I get {5=>2, 1=>2} the keys being the bar_id and the values the count of how many have that id.使用Foo.group(:bar_id).count我得到{5=>2, 1=>2}键是bar_id和值是多少具有该 id 的计数。

What I'm trying to do is, group Foo on Bar#name with an array of Foo s as the values.我正在试图做的是,一群FooBar#name与数组Foo S作为值。

{
 'name1' => [#<Foo:0x00007fbd5894f698 id:1, name: 'thing'...}, ...],
 'name2' => [#<Foo:0x00017fbd5894f698 id:5, name: 'thing'...}, ...],
 ...
}

With Foo.joins(:bar).group('bars.name').count I am able to return {"name1"=>2, "name2"=>2} But not an array of the Foo models.使用Foo.joins(:bar).group('bars.name').count我可以返回{"name1"=>2, "name2"=>2}但不是 Foo 模型的数组。 I know it's because of the count.我知道这是因为计数。 But without the count it simply returns #<Foo::ActiveRecord_Relation:0x3fdeac1cc274>但是没有计数它只是返回#<Foo::ActiveRecord_Relation:0x3fdeac1cc274>

I see a lot of suggestions using Enumerable#group_by .我看到很多使用Enumerable#group_by的建议。 I don't want to use an enumerable as I'm using ActiveRecord and as the records increase, it will drastically slow down the look up.我不想使用可枚举,因为我正在使用 ActiveRecord 并且随着记录的增加,它会大大减慢查找速度。

I've noticed that you're using PostgreSQL.我注意到您正在使用 PostgreSQL。 Why not then use the json aggregation functions.为什么不使用json 聚合函数。 It a bit differs from your desired result, but still contains the same information:它与您想要的结果略有不同,但仍包含相同的信息:

Bar
  .joins(:foos)
  .group("bars.name")
  .pluck("bars.name", "json_agg(json_build_object('id', foos.id, 'name', foos.name))")
  .to_h

The result is going to be:结果将是:

{
 'name1' => [{id:1, name: 'thing'}, ...],
 'name2' => [{id:5, name: 'thing'}, ...],
 ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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