You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何确保重定向时传递ID?提交评论后无法跳转至Challenge详情页

问题场景与报错详情

我在Challenges的show.html.erb页面中,展示了对应Challenge下的所有Pun,每个Pun下方会渲染其关联的所有Comment,同时每个Pun下方都设有「添加评论」按钮。

添加评论的表单URL如下,能看到challenge_id已经被正确传入:

http://localhost:4000/puns/109/comments/new?challenge_id=22&user_id=2

但目前遇到的问题是:成功提交评论后,无法跳转回Challenge详情页,触发了以下错误:

ActionController::ActionControllerError in CommentsController#create
Cannot redirect to nil!

我的CommentsController中的create方法代码如下:

def create
  user_id = current_user.id if current_user
  respond_to do |format|
    if @pun.comments.create!(comment_params.merge(user_id: user_id, pun_id: @pun.user_id))
      format.html { redirect_to @challenge }
    else
      format.html { render :new, notice: 'Comment not saved. Something went wrong.' }
      format.json { render json: @challenge.errors, status: :unprocessable_entity }
    end
  end
end
问题分析与修复方案

这个报错的核心原因很直接:你在执行redirect_to @challenge时,@challenge变量是nil!虽然表单URL里携带了challenge_id参数,但你的create方法完全没有去获取并赋值这个变量,自然没法跳转到对应的Challenge页面。

另外我还发现代码里有个小错误:你给pun_id赋值成了@pun.user_id,这明显不对——应该是@pun.id才对,别把Pun的ID和创建Pun的用户ID搞混了。

修复后的create方法代码如下:

def create
  user_id = current_user.id if current_user
  # 新增这行:从请求参数中获取challenge_id,查询对应Challenge实例
  @challenge = Challenge.find(params[:challenge_id])
  respond_to do |format|
    # 修正pun_id的赋值,改为@pun.id
    if @pun.comments.create!(comment_params.merge(user_id: user_id, pun_id: @pun.id))
      format.html { redirect_to @challenge, notice: 'Comment added successfully!' }
    else
      # 这里也建议修正:应该渲染评论的错误信息,而不是@challenge的
      format.html { render :new, notice: 'Comment not saved. Something went wrong.' }
      format.json { render json: @pun.comments.last.errors, status: :unprocessable_entity }
    end
  end
end

额外提醒两点:

  • 确保你的comment_params方法已经允许了评论内容相关的参数(比如:content),否则评论内容会无法被保存;
  • 确认CommentsController的new方法中也正确获取了@challenge,保证表单页面的上下文正常。

内容的提问来源于stack exchange,提问作者matski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:55:05