我在使用scaffold
的教程中发现了这个问题undefined method `save' for nil:NilClass
我不知道为什么会这样,因为我没有改变任何东西,当我生成Comment类时,这个方法会由脚手架自动编写。发生了什么?我是业余爱好者,所以我不知道在这里展示什么代码。 非常感谢你的帮助。
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :edit, :update, :destroy]
def create
@link = Link.find(params[:link_id])
@comment = @link.comments.new[comment_params]
@comment.try[:user] = current_user
respond_to do |format|
if @comment.save
format.html { redirect_to @link, notice: 'Comment was successfully created.' }
format.json { render json: @comment, status: :created, location: @comment }
else
format.html { render action: "new" }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# DELETE /comments/1
# DELETE /comments/1.json
def destroy
@comment.destroy
respond_to do |format|
format.html { redirect_to comments_url, notice: 'Comment was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_comment
@comment = Comment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def comment_params
params.require(:comment).permit(:link_id, :body, :user_id)
end
end
答案 0 :(得分:2)
未定义的方法`save'代表nil:NilClass
我认为错误是由于以下行
@comment = @link.comments.new[comment_params]
应该是
@comment = @link.comments.new(comment_params)