嗨,我阅读了Michael Hartl的RAILSTUTORIAL一书,我有一个关于他如何构建用户的展示页面的问题。
页面应该列出用户发布的所有帖子。
UsersController
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>posts/_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对象的users视图中呈现一个部分,但它要求它为@post,并且由于在用户控制器的show操作中没有定义@post,所以我得到了一个零错误。
从用户的控制器转到post视图并使用局部变量对我来说似乎很奇怪,如果我正确理解局部变量,它就不能在该视图的外部使用。有没有办法将该视图中post的值分配给users视图中的@post?
谢谢你的帮助
发布于 2011-04-27 10:03:35
您需要在partial中使用局部变量,并在locals散列中为其赋值。这一行是迭代数组并呈现部分的快捷方式。我不确定这在Rails 3中是否还有效:
<%= render @posts %>我会这样做的:
<% @posts.each do |post| %>
<%= render 'posts/post', :post => post %>
<% end %>稍微老一点的渲染偏导数的方法:
<% @posts.each do |post| %>
<%= render :partial => 'posts/post', :locals => {:post => post} %>
<% end %>https://stackoverflow.com/questions/5798482
复制相似问题