简体   繁体   中英

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.

class Foo < ApplicationRecord
  belongs_to :bar
  ...

Foo has attributes of id and name and bar_id

and

class Bar < ApplicationRecord
  has_many :foos
  ...

Bar has the attributes, id and name .

When I simply try Foo.group(:bar_id) I get #<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.

What I'm trying to do is, group Foo on Bar#name with an array of Foo s as the values.

{
 '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. I know it's because of the count. But without the count it simply returns #<Foo::ActiveRecord_Relation:0x3fdeac1cc274>

I see a lot of suggestions using 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.

I've noticed that you're using PostgreSQL. Why not then use the json aggregation functions. 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'}, ...],
 ...
}

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