私はユーザーが自分の投稿にコメントする方法を作り出そうとしています。現在のところ、私のホームページにすべてのユーザー投稿が表示され、ユーザープロフィールには現在のユーザーだけが投稿されています。私はコメントがユーザーのプロファイルの投稿にのみ表示されるようにしたいと思います。私はユーザープロファイルにコメントフォームを追加しようとしましたが、Nilのための未定義のメソッド `comments 'があります:NilClassエラー。定義されていないメソッドnilのための `comments ':NilClass
私comments_controllerは私が私のコメントモデルが
のように見える<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 %>
のように見えるユーザプロファイルにレンダリングしています部分(_comment_form.html.erb)を持っている
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post])
@comment = @post.comments.create(params[:comment])
redirect_to post_path(@post)
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>
でも同じエラーが発生しました。 –