mercredi 14 août 2019

How to group and sum by foreign key?

I have these two models in my Rails app:

class Person < ApplicationRecord

  has_many :payments

end


class Payment < ApplicationRecord

  belongs_to :person

end


How can I group the payments by person and order them by amount?

Right now I have...

Payment.group(:person_id).sum("amount")

...which works but doesn't include the persons' names. It returns something like this:

{ 1 => 1200.00, 2 => 2500.00 }

How can I replace the IDs / integers with the persons' names and also sort the whole thing by amount?

Thanks for any help!

Aucun commentaire:

Enregistrer un commentaire