user1656427
user1656427

Reputation: 51

ActiveRecord: Count of objects in has_many relation

I noticed something that I can't understand. Given the following:

class Parent < ActiveRecord::Base
  has_many :children
end

Class Child < ActiveRecord::Base
  belongs_to :parent
end

Now, let's say I'll fetch all parents and I want to know how many children each of the parents has, I'll do something like:

>>> Parent.all(:include => :children).each { |parent| print parent.children.count }
Parent Load ...
Child Load ...
...
(0.2ms)  SELECT COUNT(*) FROM "children" WHERE "children"."parent_id" = 46
...

It will generate a Query for each parent, even if I include the children as above in the query. What fixes it is if I call .to_a on children:

>>> Parent.all(:include => :children).each { |parent| print parent.children.to_a.count }

And that is strange, because if I fetch the class of children it tells me "Array":

>>> parent.children.class
Array

And if I check the class after the call of "to_a" I again have an Array

>>> parent.children.to_a.class
Array

Why is count acting so different?

Upvotes: 1

Views: 759

Answers (1)

GeekOnCoffee
GeekOnCoffee

Reputation: 1165

Try .size instead of .count. ActiveRecord does a SQL count, rather than determining the size of the collection it has already fetched.

Upvotes: 1

Related Questions