Rails has_many :through sum attribute on “child objects” --> SQL Toughy

好久不见. 提交于 2019-12-19 09:07:53

问题


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.


回答1:


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>


来源:https://stackoverflow.com/questions/16052191/rails-has-many-through-sum-attribute-on-child-objects-sql-toughy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!