mercredi 13 janvier 2016

Doing conditional count with ActiveRecord objects

Food.where(meat: true).count do |food|
  food.chunky?
end

just does the same thing as Food.where(meat: true).count, as an SQL-style count is being done, rather than an Enumerable#count type of count.

Is there any way of doing an Enumerable#count type of count other than tacking on an each, like the following?

Food.where(meat: true).each.count do |food|
  food.chunky?
end

(Yes, I realise doing food.chunky? involves creating food objects and calling a method on them, rather than doing everything at the database level - sometimes it can't be avoided)

Aucun commentaire:

Enregistrer un commentaire