我對Active Record關聯存在問題,並且想知道是否有人可以將我指向正確的方向。我會盡力解釋我的問題,但我甚至不知道該怎麼稱呼它。ActiveRecord關聯:通過多個表獲取數據
我在我的數據庫中有三個表都是相互關聯的,我需要從一個視圖文件中的三個表中的每一個調用信息。
在主題內可以有多個帖子,每個帖子(和主題)都有一個用戶附加到它。我需要能夠使用Post和Topics在用戶表中調用數據。
問題:如何通過多個模型從表中獲取數據。 (主題 - >發表 - >用戶)
模型
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
在視圖/主題/ show.html,我試圖顯示誰張貼的用戶。當我嘗試獲取信息時,它給我提供了「名稱」未定義方法的錯誤。我想是這樣的:
http://i44.tinypic.com/1z4kapj.png
舉例:1後,通過用戶名
查看/雲淡風輕/ 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 %>
順便說一句,你寫了「控制器」,但這些都是你發佈的模型。我假設這只是一個錯字。 –
你是對的,謝謝。 – Lindsiria