RailsTutorial.org书籍设计问题

时间:2011-04-27 01:51:29

标签: ruby-on-rails ruby-on-rails-3 view local-variables

您好我参与了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>

文章/ _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,并且由于在用户控制器的show动作中没有定义@post,我得到一个nil错误。

从用户的控制器转到posts视图并使用局部变量对我来说似乎很奇怪,如果我理解正确的局部变量就不能在局外视图中使用。有没有办法在该视图中将post的值分配给用户视图中的@post?

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您需要在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 %>