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

Rails中Comments的index方法正常,show方法为何无法工作?

问题原因及解决办法

1. 路由路径错误

你的comments是嵌套在forum_threads下的资源路由,所以show方法的正确请求路径应为:
GET /forum_threads/:forum_thread_id/comments/:id
而非你注释中写的GET /Comments/:id。用错误路径请求时,Rails无法匹配到对应路由,直接导致请求失败。

你可以在终端运行rails routes命令,查看完整路由列表,确认comments的show路由实际路径。

2. 控制器变量名大小写不匹配

在show方法中,你定义的变量是@Comment(大写C开头),但渲染时调用的是@comment(小写c开头):

def show
    @Comment = Comment.find(params[:id])
    render json: @comment # 变量名与定义不一致
end

这会导致Rails找不到@comment变量,返回nil或抛出undefined local variable or method错误。按照Rails编码约定,变量名统一用小写开头:

def show
    @comment = Comment.find(params[:id])
    render json: @comment
end

3. 额外优化建议:index方法查询规范

你的index方法使用了字符串拼接式的where条件:

@Comments = Comment.where("ForumThread_id = ?", params[:forum_thread_id])

首先,Rails默认数据库字段为蛇形命名(forum_thread_id),若你的实际字段是该格式,原写法会导致查询错误。其次,更符合Rails规范的写法是符号式查询:

@comments = Comment.where(forum_thread_id: params[:forum_thread_id])

同时变量名统一为小写开头,契合Rails编码习惯。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:10:27