Rails 如何查询拥有最多超级英雄的团队并在视图中展示对应信息
实现方案
1. 逻辑层代码调整(不要把查询逻辑写在视图中,推荐放到控制器或模型封装)
Rails内置了查询方法可以直接实现需求,仅需一次SQL查询,避免N+1性能问题:
首先在你渲染对应视图的控制器Action中,添加查询代码,将结果通过实例变量传给视图:
@top_team = current_user.teams .left_joins(:superheroes) .group('teams.id') .select('teams.*, COUNT(superheroes.id) as superhero_count') .order('superhero_count DESC') .first
如果想要代码更简洁,也可以把查询逻辑封装到User模型中:
# app/models/user.rb class User < ApplicationRecord has_many :superheroes has_many :teams, through: :superheroes # 新增方法:获取当前用户关联的、超级英雄数量最多的团队 def team_with_most_superheroes teams.left_joins(:superheroes) .group('teams.id') .select('teams.*, COUNT(superheroes.id) as superhero_count') .order('superhero_count DESC') .first end end
封装后控制器中只需写:
@top_team = current_user.team_with_most_superheroes
2. 视图层代码调整
直接使用实例变量渲染即可,无需循环遍历所有团队,同时添加无团队的边界情况兼容:
<% if @top_team %> 拥有最多超级英雄的团队是【<%= @top_team.name %>】,该团队的超级英雄总数量为【<%= @top_team.superhero_count %>】。 <% else %> 暂未查询到关联的团队信息 <% end %>
如果你的团队表存储名称的字段不是name,替换成对应字段名即可
原理解释
left_joins(:superheroes)左连接超级英雄表,保证没有超级英雄的空团队也会被纳入统计group('teams.id')按团队ID分组,分别统计每个团队的超级英雄数量select自定义返回字段,除了团队本身属性外,额外新增统计出来的超级英雄数量,别名为superhero_countorder按超级英雄数量倒序排序,取第一条即为数量最多的团队
内容的提问来源于stack exchange,提问作者Paparoo
相关产品推荐
相关产品推荐

