我是 Rails 新手,正在阅读入门指南。我通读了这个关于指南的类似问题,但它似乎并不相关。
我被困在第 6.3 节,我们试图让用户在博客文章中添加评论。我在 post show 视图中添加了一个评论表单,之前它运行良好,但现在引发了以下错误。问题是什么?
NoMethodError in Posts#show
Showing /Users/.../Desktop/Rails Blog/blog/app/views/posts/show.html.erb where line #24 raised:
undefined method `comments' for nil:NilClass
Extracted source (around line #24):
21 <% end %>
22
23 <h2>Add a comment:</h2>
24 <%= form_for([@post, @posts.comments.build]) do |f| %>
25 <p>
26 <%= f.label :commenter %><br />
27 <%= f.text_field :commenter %>
post_controller.rb:
class PostsController < ApplicationController
def index
@posts = Post.all
end
def new
@post = Post.new
end
def create
@post = Post.new(params[:post].permit(:title, :text))
if @post.save
redirect_to @post
else
render 'new'
end
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update(params[:post].permit(:title, :text))
redirect_to @post
else
render 'edit'
end
end
def show
@post = Post.find(params[:id])
end
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to posts_path
end
private
def post_params
params.require(:post).permit(:title, :text)
end
end
评论控制器:
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment].permit(:commenter, :body))
redirect_to post
end
end
post.show.html.erb:
<p>
<strong>Title:</strong>
<%= @post.title %>
</p>
<p>
<strong>Text:</strong>
<%= @post.text %>
</p>
<h2>Comments</h2>
<% @post.comments.each do |comment| %>
<p>
<strong>Commenter:</strong>
<%= comment.commenter %>
</p>
<p>
<strong>Comment:</strong>
<%= comment.body %>
</p>
<% end %>
<h2>Add a comment:</h2>
<%= form_for([@post, @posts.comments.build]) do |f| %>
<p>
<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
</p>
<p>
<%= f.label :body %><br />
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<%= link_to 'Back', posts_path %>
<%= link_to 'Edit', edit_post_path(@post) %>