You should put all this in a ||= begin ... end block so the query evaluatation is only done once.