Xodarap
Xodarap

Reputation: 11859

ActiveRecord count after select

I have a pagination helper like this:

  def paginate(collection)
    count = collection.count
    collection.offset(@offset).limit(@per_page)
  end

for collection I only want to select certain fields, but the behavior of count changes if I do a select. Is there a way that I can pass in e.g. Model.all.select(:foo, :bar) as collection here?

Upvotes: 2

Views: 627

Answers (1)

eirikir
eirikir

Reputation: 3842

Its true that ActiveRecord count will, without arguments, query the COUNT based on the attributes specified with select:

Model.select(:attribute).count
   (1987.0ms)  SELECT COUNT("models"."attribute") FROM "models"

However you can override this by passing a SQL or attribute argument to count:

Model.select(:attribute).count("*")
   (8.3ms)  SELECT COUNT(*) FROM "models"
Model.select(:attribute).count(:id)
   (1.3ms)  SELECT COUNT("models"."id") FROM "models"
Model.select(:attribute).count("DISTINCT id")
   (3.8ms)  SELECT COUNT(DISTINCT id) FROM "models"

Note that the first of these generates the same SQL as count without arguments on a scope without a select:

Model.count
   (1.9ms)  SELECT COUNT(*) FROM "models"

Upvotes: 2

Related Questions