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 Foos 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.
ActiveRecord_Relationis a set of records. You need to invoketo_aon it, or iterate over it.to_a:ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: column "foos.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT "foos".* FROM "foos" INNER JOIN "bars" ON "... ^ : SELECT "foos".* FROM "foos" INNER JOIN "families" ON "bars"."id" = "fooss"."bar_id" GROUP BY bars.name from /2.5.0/lib/ruby/gems/2.5.0/gems/activerecord-5.2.0/lib/active_record/connection_adapters/postgresql_adapter.rb:603:inasync_exec'`