以下是控制器
class CommentsController < InheritedResources::Base
def comment_params
params.require(:comment).permit(:name, :email, :body, :post_id)
end
def create
@comment = Comment.new(params[:comment_params])
if @comment.save
flash[:notice] = 'Comment was succesfully posted.'
redirect_to(@comment.post)
else
flash[:notice] = "Error creating comments: #{@comment.errors}"
redirect_to(@comment.post)
end
end
end
我所看到的只是,
ActionController::ActionControllerError in CommentsController#create
Cannot redirect to nil!
Rails.root: c:/sites/myrubyblog
Application Trace | Framework Trace | Full Trace
app/controllers/comments_controller.rb:13:in `create'
通过评论else块中的redirect_to将通过另一个错误说错过模板!
尝试过以前提出的问题中的一些解决方案,但没有任何帮助!
答案 0 :(得分:1)
在你的else块中也会重定向到@ comment.post,即使它没有保存。所以基本上它是零。 我不认为你的评论被保存了。尝试这样做以确定是否有任何错误
if @comment.save! # this will show errors if any
...
else
post = Post.find(params[:post_id])
redirect_to post
end
我假设你的params中有post_id。如果不是@ comment.post也将是零。导致if和else块中的错误。
答案 1 :(得分:0)
else
flash[:notice] = "Error creating comments: #{@comment.errors}"
redirect_to(@comment.post) <--
end
如果保存失败,它会尝试重定向到@comment.post
,但它没有,因为您没有正确设置post_id
@comment = Comment.new(params[:comment_params])
哪个应该是
@comment = Comment.new(comment_params)
答案 2 :(得分:0)
不是params[:comment_params]
而是comment_params
,您应该将create
操作更改为此操作,并确保设置post_id
:
class CommentsController < InheritedResources::Base
def comment_params
params.require(:comment).permit(:name, :email, :body, :post_id)
end
def create
@comment = Comment.new(comment_params)
if @comment.save
flash[:notice] = 'Comment was succesfully posted.'
redirect_to(@comment.post)
else
flash[:notice] = "Error creating comments: #{@comment.errors}"
redirect_to(@comment.post)
end
end
end