访问/articles/new时触发undefined method `articles_path'错误求助
问题原因及解决方案
错误原因
form_for(@article) 会遵循Rails的RESTful约定自动生成表单提交路径:当@article是新实例时,表单会以POST请求提交到articles_path,但你的路由配置里没有定义这个命名路由,而是手动指定了post 'articles/create',导致视图找不到articles_path方法。
解决步骤
1. 改用RESTful路由(推荐)
修改config/routes.rb,替换原有路由为RESTful风格的资源路由:
resources :articles, only: [:new, :create, :show]
这个配置会自动生成符合Rails规范的命名路由:
- GET
/articles/new→articles#new - POST
/articles→articles#create(对应articles_path) - GET
/articles/:id→articles#show(对应article_path)
2. (可选)手动修正路由命名
如果不想使用RESTful路由,需要给POST路由添加命名,让form_for能匹配到对应的路径:
get 'articles/new', to: 'articles#new' post 'articles', to: 'articles#create', as: :articles get 'articles/:id', to: 'articles#show', as: :article
这里将POST路径调整为/articles并命名为articles,匹配form_for的默认期望。
3. 补充参数白名单方法
检查你的Articles控制器是否定义了article_params方法(用户提供的代码中未包含,这是创建记录的必需步骤):
private def article_params params.require(:article).permit(:title, :body) end
完成以上修改后,刷新页面即可正常访问/articles/new并提交表单。
内容的提问来源于stack exchange,提问作者Muhammad Ramzan
相关产品推荐
相关产品推荐

