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

Rails嵌套路由下测试create动作提示No route matches index错误

问题原因
  • 你的characters是嵌套在stories下的资源,对应的路由helper story_characters_path 要求必须传入父资源story的ID作为参数,才能生成正确的路径/stories/:story_id/characters。
  • 你现在将story_id放在了POST请求的参数中,没有传递给路由helper,导致helper无法拼接出合法的URL,路由匹配失败时会默认指向同路径模式的GET请求(对应index动作),因此抛出了缺少story_id、匹配index动作的报错。
解决方法

将@story或story_id作为参数传入story_characters_path即可,修改后的测试代码如下:

test "can create a new character" do
  params = { character: { name: "Billy" } }
  # 父资源ID传入路由helper生成正确路径
  post(story_characters_path(@story), params: params)

  # ... 后续断言
end

你也可以显式指定key的形式传参,效果完全一致:
story_characters_path(story_id: @story.id)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:36:03