ユーザーに自分の投稿にコメントしてもらう方法を作成しようとしています。現在、すべてのユーザー投稿がホームページに表示され、ユーザープロファイルには現在のユーザー投稿のみが表示されます。コメントがユーザープロファイルの投稿にのみ表示されるようにしたいと思います。ユーザープロファイルにコメントフォームを追加しようとしましたが、nil:NilClassエラーに対して未定義のメソッド`comments'が表示されました。
私の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>