我是Rails的新手,正在研究Getting Started Guide。我通读了this关于指南的类似问题,但似乎并不相关。
我被困在第6.3节,我们试图让用户在博文中添加评论。我已经在帖子显示视图中添加了一个评论表单,之前工作正常,但现在引发了以下错误。有什么问题?
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 %>
posts_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
comments_controller:
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
posts.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) %>
答案 0 :(得分:2)
你有@posts
。该变量称为@post
。放下“s”。