class Homie < ApplicationRecord has_many :money_moves def self.cash(importance) totals = Homie.all.joins(:money_moves).group(:id).order(:id).sum(:amount) result = [] Homie.where(["importance > ?", importance]).map do |homie| total = totals.fetch(homie.id, 0) { homie: homie, amount: total } end end end