Rails报错:undefined method `category_documentations_path',路由用comments而非documentations
解决NoMethodError: undefined method `category_documentations_path'的问题
这个错误的原因非常明确:你的视图代码(/categories/show.html.haml第6行)调用了category_documentations_path这个路由辅助方法,但你的routes.rb里根本没有配置对应的嵌套documentations资源,反而配置的是comments,所以Rails找不到这个方法,才会贴心提示你是不是想调用category_comments_path。
下面分两种情况给出解决方案:
情况1:你确实想给Category添加Documentation嵌套资源
如果你的需求是在Category下创建Documentation的嵌套表单,那需要修改routes.rb,把原来的comments嵌套资源替换成documentations:
Rails.application.routes.draw do # 其他路由配置... resources :categories do resources :documentations # 替换原来的resources :comments end end
修改完成后,运行rails routes命令,你就能看到生成的category_documentations_path等路由辅助方法了,此时视图里的调用就会正常工作。
情况2:你只是视图代码写错了(本来应该用Comments)
如果你的需求还是围绕Comments展开,只是不小心在视图里把category_comments_path写成了category_documentations_path,那直接修改show.html.haml第6行的代码,把错误的方法名改成category_comments_path即可。
小提示
以后遇到路由相关的NoMethodError,都可以先运行rails routes命令查看所有可用的路由辅助方法,确认你调用的方法是否真的存在,能快速定位这类拼写或配置不匹配的问题。
内容的提问来源于stack exchange,提问作者Cédric Seyer
相关产品推荐
相关产品推荐

