Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 显示在索引中具有并属于许多关联_Ruby On Rails_Activerecord - Fatal编程技术网

Ruby on rails 显示在索引中具有并属于许多关联

Ruby on rails 显示在索引中具有并属于许多关联,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,嘿,我是Rails的新手,所以请容忍我,谢谢 我有两种型号: class User < ApplicationRecord has_and_belongs_to_many :sports end class Sport < ApplicationRecord has_and_belongs_to_many :users end 我的用户有几种不同的运动,他们可以选择每种运动。我只是想在一张表中显示所有用户,以及他们从事的运动。然而我能够获得任何东西而不出错的唯一方法是使用如下

嘿,我是Rails的新手,所以请容忍我,谢谢

我有两种型号:

class User < ApplicationRecord
 has_and_belongs_to_many :sports
end

class Sport < ApplicationRecord
 has_and_belongs_to_many :users
end
我的用户有几种不同的运动,他们可以选择每种运动。我只是想在一张表中显示所有用户,以及他们从事的运动。然而我能够获得任何东西而不出错的唯一方法是使用如下所示的当前用户。我已经想了好几个小时了。。。我知道这将是愚蠢的简单,但我只是不明白它,甚至不知道如何走在正确的方向

# users_controller.rb
def index
 @users = User.all
 @sports = current_user.sports
end

# users/index.html.erb
<% @users.each do |user| %>
  <tr>
   <td><%= link_to user.name, user %></td>
   <td><%= link_to user.email, user %></td>
    <% @sports.each do |s| %>
     <td><%= s.name %></td>
    <% end %>
  </tr>
 <% end %>
这是我当前的代码,但很明显,这只显示登录用户关联,并为其他用户重复此代码,如下所示:

<table>
<tr>
<th>Name</th>
<th>Sport 1:</th>
<th>2:</th>
</tr>

<tr>
<td>User 1 (current_user)</td>
<td>Football</td>
<td>Running</td>
</tr>

<tr>
<td>User 2</td>
<td>Football (User 1's Sports)</td>
<td>Running </td>
</tr>
</table>

提前感谢。

您可以尝试使用以下命令并删除@sports=current\u user.sports:


在遍历每个用户时使用user.sports将导致对数据库进行N+1查询。您可以将控制器方法更改为

def index
 @users = User.all.eager_load(:sports)
end
然后是html

<% user.sports.each do |s| %>
 <td><%= s.name %></td>
<% end %>
这将在sports table上加载用户以及left_outer_join,这将在数据库上节省大量额外的查询

有关信息,请参阅此


谢谢

谢谢!正如所料,它非常简单
<% user.sports.each do |s| %>
 <td><%= s.name %></td>
<% end %>