需要来自许多人的数据:许多人加入Rails视图

时间:2009-08-19 10:11:41

标签: ruby-on-rails database has-and-belongs-to-many

在大多数情况下,它可能不是最佳解决方案,但我想要一个包含数据表格的表格。

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

我认为最好在Controller中使用Media查找方法,但我不知道究竟是多么准确,更可能的解决方案可能是将媒体和用户作为参数的辅助方法。

您认为最佳解决方案是什么?

1 个答案:

答案 0 :(得分:1)

这种关联属于你的模型,有很多通过关系是完美的。

class User < ActiveRecord::Base
  has_many :ratings
  has_many :media, :through => :ratings
end

class Media < ActiveRecord::Base
  has_many :ratings
  has_many :users, :through => ratings
end

class Rating < ActiveRecord::Base
  belongs_to :user
  belongs_to :media
end

然后你可以访问

media.name media.comment 

然后也可以访问

user.ratings

或:

<% media.users.each do |user| %>
  ## Do stuff with user.ratings array
<% end %>

你也可以:

media.ratings.each do |rating|
  rating.your_attribute
  rating.user.your_attribute
end