【发布时间】:2011-04-27 01:51:28
【问题描述】:
您好,我阅读了 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>
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 对象的用户视图中渲染一个部分,但它要求它作为 @post 并且由于在用户控制器的显示操作中没有定义 @post 我得到一个 nil 错误。
从用户控制器转到帖子视图并使用局部变量对我来说似乎很奇怪,如果我正确理解局部变量,则不能在该视图之外使用。有没有办法将该视图中的帖子值分配给用户视图中的@post?
感谢您的帮助
【问题讨论】:
-
请指出发生这种情况的部分,以便我们可以调试与您相同的东西。
-
我通过使用局部变量并将其传递给其他视图来解决这个问题,当我确实定义了@post 时,我将它作为本地变量发送。如果您有时间调试其他东西,我在这里提出了一个新问题,关于如何从 rails 教程书转到嵌套路由并保持提要完好无损。 *.com/questions/5800399/…
-
但是如果你确实想看这个,它在本章中的清单 11.17,ruby.railstutorial.org/chapters/user-microposts#top 基本上没有解释,我不知道另一种方法来完成它,所以我已经将其与局部变量一起保存。我应该切换到下面的示例而不是 并以长代码方式执行,因为这样会更快地呈现??
标签: ruby-on-rails ruby-on-rails-3 view local-variables