问题描述
我有三个,一对许多
的关系,一个的has_many:通过
的关联和对象与属性我想总结。
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
.)
最近我现在可以得到的是 @ league.homeruns.sum(:英尺)
(显示多少在每个联盟本垒打总距离),但我想这样做在团队的水平,筛选的联赛。
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.
有意义吗?任何帮助将是深深的AP preciated。
Make sense? Any help would be deeply appreciated.
推荐答案
如果您添加:团队的has_many:本垒打,通过:用户
,然后你可以用 team.homeruns.sum(:英尺)
来让你每队以后有什么,对不对?或许,这将是最好的移动到这一点的方法,你的小组
型号:
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
要然后列出各队的特定联赛
,只是通过各小组
属于该<$迭代C $ C>联赛在视图中,包裹在任何你想要的HTML。例如,以显示它作为表
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>
这篇关于导轨的has_many:在与QUOT通过总和属性;子对象&QUOT; - &GT; SQL Toughy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!