通常的博客,即Posts
和Comments
...
评论属于帖子......
帖子'控制器是针对帖子的所有典型操作。
帖子'模型has_many
评论
帖子的观点显示很好......
然后我创建了注释控制器,模型和仅两个部分视图文件,即_form.html.erb
和_comment.html.erb
...
在帖子的show.html.erb
中,我把它们都放在这样:
<h2>Recent Comments</h2>
<%= render @comment.comments %>
<h2>Add Comments</h2>
<%= render 'comments/form' %>
当我遇到这个麻烦时,即当我点击Post&#39的节目链接时出现此错误...我收到此错误:
NoMethodError in Posts#show
&amp; undefined method
评论&#39;对于nil:NilClass in reference to this line
&lt;%= render @ comment.comments%&gt;`我不知道如何解决它......
发布控制器
class PostsController < ApplicationController
def index
@posts = Post.all
if @posts.blank?
flash[:alert] = "No posts have been created."
else
@posts
end
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update(post_params)
flash[:notice] = "Post has been updated."
redirect_to @post
else
flash.now[:alert] = "Post has not been updated."
render "edit"
end
end
def create
@post = Post.new(post_params)
if @post.save
flash[:notice] = "Post has been created."
redirect_to @post
else
flash[:notice] = "Post has not been created."
end
end
def new
@post = Post.new
end
def show
@post = Post.find(params[:id])
end
def destroy
@post = Post.find(params[:id])
@post.destroy
flash[:notice] = "Post has been deleted."
redirect_to posts_path
end
private
def post_params
params.require(:post).permit(:title, :author, :body)
end
end
评论控制器
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comment_params)
redirect_to post_path(@post)
end
private
def comment_params
params.require(:comment).permit(:author, :body)
end
end
评论_comment.html.erb
<p>
Author:
<%= comment.author %>
</p>
<p>
Body:
<%= comment.body %>
</p>
如果需要进一步的信息,请告诉我。
答案 0 :(得分:2)
注意你的错误试图告诉你的事情:
NoMethodError in Posts#show undefined method 'comments' for nil:NilClass regarding <%= render @comment.comments %>
它告诉你NilClass没有方法comments
。这意味着@comment
为零。 @comment
为零,因为您从未在相应的Posts#show
操作中定义该变量。在那里,您只有一个@post
变量。
我的猜测是你真正打算做的是:<%= render @post.comments %>