nil的未定义方法`comments':NilClass

时间:2011-08-09 18:03:59

标签: ruby-on-rails ruby ruby-on-rails-3 comments posts

我正在尝试创建一种让用户评论我的帖子的方法。目前,我的所有用户帖子都显示在我的主页上,然后在用户个人资料中仅显示当前用户的帖子。我想拥有它,以便评论只出现在用户个人资料中的帖子上。我试图在用户配置文件中添加一个注释表单但我得到一个未定义的方法`comments'为nil:NilClass错误。

我的comments_controller看起来像

class CommentsController < ApplicationController
  def create
    @post = Post.find(params[:post])
    @comment = @post.comments.create(params[:comment])
    redirect_to post_path(@post)
end

我有一个部分(_comment_form.html.erb)我在用户个人资料中呈现,看起来像

<h2>Add a comment:</h2>
<%= form_for ([@post, @post.comments.build]) do |f| %>
   <div class="field">
    <%= f.label :commenter %><br />
    <%= f.text_field :commenter %>
   </div>
   <div class="field">
    <%= f.label :body %><br />
    <%= f.text_area :body %>
   </div>
   <div class="actions">
    <%= f.submit %>
   </div>
<% end %>

我的评论模型看起来像

class Comment < ActiveRecord::Base
  belongs_to :post
end

我的帖子模型看起来像

class Post < ActiveRecord::Base
 attr_accessible :content

 belongs_to :user

 validates :content, :presence => true
 validates :user_id, :presence => true
 validates :user, :presence => true
 validates :title, :presence => true

 has_many :comments

 default_scope :order => 'posts.created_at DESC'
end

我的用户个人资料看起来像show.html.erb

<table class="profile" summary="Profile information">
  <tr>
    <td class="main">
    <h1>
        <%= gravatar_for @user %>
        <%= @user.name %>
    </h1>
    <% unless @user.posts.empty? %>
        <table class="posts" summary="User posts">
            <%= render @posts %>
            <%= render 'comments/comment_form' %>
        </table>    
    <% end %>
    </td>
    <td class="sidebar round">
  <strong>Name</strong> <%= @user.name %><br />
  <strong>URL</strong>  <%= link_to user_path(@user), @user %><br />
  <strong>Tasks</strong> <%= @user.posts.count %>
    </td>
  </tr>
</table>

5 个答案:

答案 0 :(得分:2)

可能是您尚未在控制器的@post方法中初始化new,而是将其用作nil。如果实际可行,请始终为新表单构建一个空模型:

def new
  @post = Post.new(params[:post])
end

答案 1 :(得分:2)

@post = Post.find_by_id(params[:post_id])

答案 2 :(得分:1)

您是否正在PostsController的show动作中初始化@post?这是必需的,因为您从CommentsController的create动作重定向。

答案 3 :(得分:1)

<%= render @posts %>

这一行应该引用@post。请注意尾随s,与代码中对它的所有其他引用相比较。

答案 4 :(得分:0)

您能看到log/development.log查看错误发生的位置吗?从问题中不清楚。但从您的代码判断,有两个可能的位置:

  1. @comment = @post.comments.create(params[:comment]) 这不太可能,因为最后一行代码是Post.find,如果找不到RecordNotFound,则会引发id

  2. <%= form_for ([@post, @post.comments.build]) do |f| %>

  3. 这很有可能,您可以执行puts @post.inspect并检查您的development.log以查看它是否为null。假设它为null,您需要在呈现Post

    的任何地方实例化_comment_form.html.erb对象
相关问题