I have three, one-to-many
relationships, a has_many :through
association and an object with an attribute I'd like to sum.
This may sound silly, but assume for example a baseball-themed app:
:league has_many :teams
:team has_many :users
:league has_many :homeruns, :through => :users
:user has_many :homeruns
What I want to do, on the league show
page is list each team
in the respective league
, and sum how many feet in homeruns each team has, cumulatively. (Feet
is an attribute on homerun
.)
The closest I can get now is @league.homeruns.sum(:feet)
(showing how much total distance in homerun per league) but I want to do this at the team level, filtered by league.
Make sense? Any help would be deeply appreciated.
If you add :team has_many :homeruns, through: :users
, you could then use team.homeruns.sum(:feet)
to get what you're after per team, right? It would probably be best to move this into a method in your team
model:
# team.rb
has_many: homeruns, through: :users
def total_homerun_distance
self.homeruns.sum(:feet)
end
To then list all the teams for a particular league
, just iterate through each team
belonging to that league
in the view, wrapped in whatever HTML you want. For example, to display it as a table:
# views/leagues/show.html.erb
<table>
<% @league.teams.each do |team| %>
<tr>
<td><%= team.name %></td>
<td><%= team.total_homerun_distance %></td>
</tr>
<% end %>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With