我是Rails的新手,並且通過Getting Started Guide工作。我通過this閱讀了關於該指南的類似問題,但看起來並不相關。Rails指南「未定義的方法'評論'爲零:NilClass」
我被困在第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) %>
你在posts.show.html.erb /第24行有一個錯字。'@posts.comments => @ post.comments' – nyzm