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