Rails无刷新发布帖子出现500内部服务器错误如何解决?
错误原因
你的报错核心是ActionView::Template::Error (First argument in form cannot contain nil or be empty),触发位置是评论表单的form_for([post, @comment])代码行,问题根源非常明确:
- 无刷新发布帖子时走的是
PostsController#create的JS响应逻辑,你只初始化了@post变量,没有初始化@comment变量,导致渲染评论表单时@comment为nil,触发500错误,新帖子自然没法追加到页面上 - 刷新页面时走的是
PostsController#index动作,这个动作里你已经提前初始化了@comment = Comment.new,所以评论表单能正常渲染,帖子也能正常显示
修复方案
二选一即可:
方案1(修改控制器,最快生效)
直接在PostsController#create的保存成功分支里添加@comment的初始化逻辑,修改后的代码如下:
def create @post = current_user.posts.build(post_params) respond_to do |format| if @post.save # 新增这一行初始化空评论对象 @comment = Comment.new format.js format.html { redirect_to posts_path, notice: 'Successfully posted.'} else format.html { redirect_to posts_path, status: :unprocessable_entity } format.json { render json: @post.errors, status: :unprocessable_entity } end end end
方案2(修改局部模板,更符合开发规范)
局部模板最好不要依赖全局实例变量,避免出现类似的上下文依赖问题,按以下步骤调整:
- 先修改评论表单
app/views/comments/_comment_form.html.haml,把实例变量@comment换成局部变量:
= form_for([post, comment]) do |f| .form-bottom-button-container .d-flex.comment-text-button .p-2.flex-grow-1 = f.text_area :content, class: "comment-text-area comment", placeholder: "Write a comment..." .p-2 = f.submit :Comment, class: "btn btn-maroon create-comment-button"
- 再修改
app/views/posts/_post_display.html.haml里渲染评论表单的代码,主动传入comment变量:
.comment-form = render "comments/comment_form", post: post, comment: Comment.new
修改完成后无刷新发布帖子功能即可正常运行。
内容的提问来源于stack exchange,提问作者bonaxl015
相关产品推荐
相关产品推荐

