需要来自多个的数据:Rails 视图中的多个连接
在大多数情况下,它可能不是最好的解决方案,但我想要一个包含 3 个表数据的表。
class Media < ActiveRecord::Base
belongs_to :user
belongs_to :type
has_many :ratings
end
class User < ActiveRecord::Base
has_many :medias
has_many :ratings
end
class Rating < ActiveRecord::Base
belongs_to :user
belongs_to :media
end
这就是我想要的视图
<table>
<tr>
<th>Name</th>
<th>Comment</th>
<th>Creator</th>
<th>Type</th>
<% for user in @users %>
<th><%=h user.login %></th>
<% end %>
</tr>
<% for media in @medias %>
<tr>
<td><%=h media.name %></td>
<td><%=h media.comment %></td>
<td><%=h media.user.login %></td>
<td><%=h media.type.name %></td>
<% for user in @users %>
<td><%=h GET_RATING (media, user) %></td>
<% end %>%>
</tr>
<% end %>
</table>
基本上我想要为每个用户对每种媒体的评级添加一个新行
我想要的是一个看起来像这样的表:
media.name media.comment ... rating(media, user).rating
我认为最好在控制器中使用带有媒体查找方法的联接,但我不这样做确切地知道如何,足够可能的解决方案可以是以媒体和用户作为参数的辅助方法。
您认为最好的解决方案是什么?
Its maybe not the best solution in most cases, but i want a table with data form 3 tables.
class Media < ActiveRecord::Base
belongs_to :user
belongs_to :type
has_many :ratings
end
class User < ActiveRecord::Base
has_many :medias
has_many :ratings
end
class Rating < ActiveRecord::Base
belongs_to :user
belongs_to :media
end
Thats the view I want
<table>
<tr>
<th>Name</th>
<th>Comment</th>
<th>Creator</th>
<th>Type</th>
<% for user in @users %>
<th><%=h user.login %></th>
<% end %>
</tr>
<% for media in @medias %>
<tr>
<td><%=h media.name %></td>
<td><%=h media.comment %></td>
<td><%=h media.user.login %></td>
<td><%=h media.type.name %></td>
<% for user in @users %>
<td><%=h GET_RATING (media, user) %></td>
<% end %>%>
</tr>
<% end %>
</table>
Basicly i want one new row for each users ratings for each media
What I want is a Table that looks like that:
media.name media.comment ... rating(media, user).rating
I think it would be better to use a join in the Controller with the Media find methods but I dont know how exactly, enougher possible solution could be helper method that takes media and user as parameters.
What do you think is the best solution for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这种关联属于您的模型,具有许多直通关系非常适合这种情况。
然后您可以访问
然后也可以访问
或:
您还可以:
This kind of association belongs in your model, a has many through relationship is perfect for this.
Then you can access
Then could also access
or:
You can also: