嗨,我阅读了 Michael Hartl 的 RAILSTUTORIAL 书,我对他如何构建用户的显示页面有疑问。
该页面应该列出用户发布的所有帖子。
用户控制器
def show
@user = User.find(params[:id])
@posts = @user.posts.paginate(:per_page => "10",:page => params[:page])
@title = @user.name
end
用户/show.html.erb
<table class="profile" summary="Profile information">
<tr>
<td class="main">
<h1><%= @user.name %></h1>
<%= render 'follow_form' if user_signed_in? %>
<% unless @user.posts.empty? %>
<table class="posts" summary="User posts">
<%= render @posts %> # this goes to posts/_post and sends the object as post
# that makes the _post view use a local variable correct?
</table> # is there a way to do with with an @post variable?
<%= will_paginate @posts %>
<% end %>
</td>
<td class="sidebar round">
<%= link_to avatar_for(@user), @user.avatar.url %><br />
<strong>Name</strong> <%= @user.name %><br />
<strong>URL</strong> <%= link_to user_path(@user), user_path(@user) %>
<strong>Posts</strong> <%= @user.posts.count %>
<%= render 'shared/stats' %>
</td>
</tr>
</table>
帖子/_post.html.erb
<tr>
<td class="post">
<span class="title"><strong><%= link_to post.title, post %></strong></span><br />
<span class="timestamp">
Posted <%= time_ago_in_words(post.created_at) %> ago. </span>
<a href="<%= likers_post_path(@post) %>">Likers</a><span id="likers"><br />
</span>
</td>
<% if current_user?(post.user)%>
<td>
<%= link_to "delete", post, :method => :delete,
:confirm => "You sure?",
:title => post.content %>
</td>
<%end%>
</tr>
我需要在使用 post 对象的用户视图中渲染一个部分,但它要求它作为 @post 并且由于在用户控制器的显示操作中没有定义 @post 我得到一个 nil 错误。
从用户的控制器转到帖子视图并使用局部变量对我来说似乎很奇怪,如果我正确理解局部变量就不能在该视图之外使用。有没有办法将该视图中的帖子值分配给用户视图中的@post?
谢谢您的帮助