Buffalo 的 generate resource 不支持嵌套路由,必须用 app.Scope() 手动实现;需在 routes.go 中先定义父资源,再用 Scope 包裹子资源,并在 handler 和模板中手动处理 post_id 参数及关联校验。

buffalo generate resource 不支持嵌套,必须手写 Scope
Buffalo 的 buffalo generate resource 命令压根没有 --parent、--nested 这类参数,它生成的永远是扁平路由,比如 /comments。你要的是 /posts/{post_id}/comments?那得自己在 config/routes.go 里用 app.Scope() 包一层。
常见错误现象:执行 buffalo g resource comments 后,以为加个 app.Resource("/posts/{post_id}/comments", CommentsResource{}) 就能跑通——不行,Buffalo 路由不支持路径参数直接混在 Resource() 第一个参数里。
- 正确写法是先注册父资源:
app.Resource("/posts", PostsResource{}) - 再用
app.Scope("/posts/{post_id}", func(app buffalo.App) { app.Resource("/comments", CommentsResource{}) }) -
{post_id}会被自动注入到c.Param("post_id"),但仅此而已——CommentsResource的所有 handler 仍按扁平逻辑运行,不会自动感知上下文
handler 里必须手动取 post_id 并校验关联
生成器创建的 actions/comments.go 默认查全部评论,比如 Index 方法里是 tx.All(&comments)。你要让它只查属于某篇 post 的评论,就得改掉。
容易踩的坑:只改了查询条件,忘了前置校验。用户可能伪造 post_id=999999,而该 post 根本不存在,或者根本不是他能访问的。
-
Show和Index:先查Post是否存在,再用db.Where("post_id = ?", c.Param("post_id")).All(&comments) -
Create:不能直接tx.Create(&c),得先查Post,再把c.Param("post_id")赋给comment.PostID字段 -
Destroy:删前必须确认该comment的PostID确实等于 URL 中的post_id,否则就是越权删除 - 如果用 pop ORM,建议在
models/comment.go加PostID uint字段和Post *Post `has_one:"posts"`关联,否则每次查都要手写JOIN
模板链接和表单 action 必须换函数,否则 404
buffalo g resource 生成的所有模板(如 templates/comments/index.plush.html)里的链接和表单,都默认用 commentsPath() 这类扁平辅助函数。它们生成的是 /comments,不是 /posts/123/comments,一提交就 404。
开箱即用的技能链路由引擎。13 条预定义链覆盖搜索、开发、审查、MLOps、法律、创意等场景,三层路由架构(触发词→SAD反馈→DAG编排),recall@10=96.97%。配置驱动(chains.yaml),零代码扩展。pip install skill-weave-chains 一键安装。
别指望模板会自动适配嵌套路径——它连你写了 Scope 都不知道。
- 所有
commentsPath()调用,要换成带参数的变体,比如postCommentsPath({post_id: post.ID}) - 表单
<form action="<%=%20commentsPath()%20%>"></form>→ 改成<form action="<%=%20postCommentsPath(%7Bpost_id:%20post.ID%7D)%20%>"></form> -
New和Edit模板里,要把post_id渲染进隐藏域或 query 参数,否则Create提交时拿不到上下文 - 辅助函数名是自动生成的,命名规则为
{parent}{child}Path,比如postCommentsPath;你可以用buffalo routes命令确认实际函数名
为什么不用 Group + Resource 组合?
有人试过写 app.Group("/posts/{post_id}").Resource("/comments", CommentsResource{}),看起来更直觉,但 Buffalo 1.x 不支持这种写法——Group() 只接受字符串前缀,不解析路径参数,{post_id} 会被当字面量处理,导致 c.Param("post_id") 拿不到值。
真正起作用的只有 Scope(),它是专门为此设计的机制。它的本质是闭包式路由作用域,会在内部自动注册带参数的子路由,并透传参数上下文。
复杂点在于:Scope 不改变 handler 的签名,也不修改结构体字段绑定逻辑。所有“嵌套感”都是靠你手动在每个 handler 里取参数、查关联、校验权限来拼出来的——Buffalo 不帮你做这层语义升维。


















