我正在尝试遵循RailsGuides,http://edgeguides.rubyonrails.org/getting_started.html
现在,在第6.4节中,我应该能够在我的博客网站中添加评论,我遇到了这个错误:
NoMethodError in Posts#show
Showing C:/Sites/blog/app/views/posts/show.html.erb where line #12 raised: </br>
undefined method `comments' for #<Post:0x3a99668
下面是我的show.html.erb中的片段
<h2>Add a comment:</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
<p>
<%= f.label :commenter %><br>
<%= f.text_field :commenter %>
下面是我的评论控制器的片段:
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(:commenter, :body)
end
end
下面是我的帖子控制器:
class PostsController < ApplicationController
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 show
@post = Post.find(params[:id])
end
def index
@posts = Post.all
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 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
请帮帮我,谢谢。
-aguds
意思是
"第12行升高:#<的未定义方法"comments";帖子:0x3a99668>"
这意味着在show.html.erb的第12行中,您正在对Post的一个对象调用comments方法,但该方法尚未定义。
因此,您需要在Post类中检查是否存在以下关系。
app/models/post.rb
has_many :comments
添加新模型后,需要重新启动服务器。(您添加了注释。)
这里的一般经验法则是对app/或config/routes之外的任何内容进行更改。rb需要重新启动。
参考:我什么时候需要在Rails中重新启动服务器?