我的 Active Record 关联有问题,想知道是否有人可以为我指明正确的方向。我会尽力解释我的问题,但我什至不知道给它起什么名字。
我的数据库中有三个相互关联的表,我需要从一个视图文件中的三个表中的每一个中调用信息。
一个主题中可以有多个帖子,每个帖子(和主题)都有一个用户附加到它。我需要能够使用 Post 和 Topics 调用 User 表中的数据。
问题:如何通过多个模型从一个表中获取数据。(主题 -> 帖子 -> 用户)
模型
class Topic < ActiveRecord::Base
belongs_to :forum
has_many :posts, :dependent => :destroy
belongs_to :user
end
class Post < ActiveRecord::Base
belongs_to :topic
belongs_to :user
end
class User < ActiveRecord::Base
has_many :topics
has_many :posts, through: => :topics
end
在 View/Topics/show.html 中,我试图显示发布的用户。当我尝试获取信息时,它给了我“名称”的未定义方法的错误。我想要的是这样的:
http://i44.tinypic.com/1z4kapj.png
示例:帖子 1 由 UserName 创建
查看/主题/Show.html.erb
<% @topic.posts.each do |post| %>
<tr>
<td class="subforum" width="80%">
<%= post.created_at %>
<div class="go-right">
<%= link_to 'Edit', edit_post_path(@post) %>
</div>
</td>
</tr>
<tr>
<td class="row1">
<%= post.users.name %>
<%= post.user_id %>
</td>
</tr>
<tr>
<td class="row1">
<%= post.content %>
</td>
</tr>
<% end %>