0

我正在尝试创建一种让用户评论我的帖子的方法。目前,我的主页上显示了所有用户帖子,然后在用户个人资料中只有当前用户的帖子。我想要它,以便评论只出现在用户个人资料中的帖子上。我试图在用户配置文件中添加评论表单,但我得到了一个未定义的方法“评论”,用于 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>
4

5 回答 5

2

可能是您没有@post在控制器的new方法中初始化,它被用作nil. 如果可行,请始终为您的新表单构建一个空模型:

def new
  @post = Post.new(params[:post])
end
于 2011-08-09T18:06:18.433 回答
2
@post = Post.find_by_id(params[:post_id])
于 2012-11-09T09:52:24.723 回答
1

您是否在 PostsController 的显示操作中初始化 @post ?这将是必需的,因为您正在从 CommentsController 的创建操作重定向。

于 2011-08-09T18:27:02.687 回答
1
<%= render @posts %>

此行应改为引用 @post。请注意尾随 s,与代码中对它的所有其他引用相比。

于 2012-11-01T12:50:52.813 回答
0

你能log/development.log看到错误发生在哪里吗?从问题中并不清楚。但是从你的代码来看,有两个可能的位置:

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

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

这很有可能,你能做一个puts @post.inspect检查你的 development.log 看看是否为空。假设它为空,你需要Post在你渲染的任何地方实例化一个对象_comment_form.html.erb

于 2011-08-09T20:41:44.163 回答