Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

Rails Active Record Group and Sum

I have a tithe and membership model

class Tithe < ApplicationRecord
  belongs_to :membership

  validates :membership_id, presence: true
  validates :amount, presence: true

end
class Membership < ApplicationRecord
    validates :firstname, presence: true
    validates :lastname, presence: true
    validates :gender, presence: true
    validates :title, presence: true

    has_one_attached :image

    has_many :tithes

end

And on the view I have

        <% @tithes.each do|tithe| %>
              <%= tithe.id %>
              <%= tithe.membership.lastname%>
              <%= tithe.amount %>
              <%= tithe.created_at %>
        <% end %>

I want to sum the tithe amount and group them by the lastname. How do i do this using Active Records?

i tried this

Tithe.joins(:membership).group("firstname").sum(:amount)

and this is what i get on the view page

{"Allan"=>0.2e3}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...