没有路线匹配“/ articles / new”

当我尝试提交表单时,它给我错误

No route matches [POST] "/articles/new" 

文件是:new.html.erb
此文件包含带有文本字段和文本区域的表单:

  

这里的url:匹配post请求,这是一个创建

表格的标题

 

表单的文本字段

 

表格的标题

 

表格的文字区域

 

路线文件是

 Rails.application.routes.draw do resources :article end 

controller是控制器,其方法是新的和创建的

每当我提交表单时给出错误,即使我使用了URL:articles_path,对于默认的post请求,我也在表单中使用了@articles,但它给了我同样的错误。 我是Rails的新手,所以我尝试了很多方法,但我找不到解决方案

 class ArticlesController < ApplicationController def new #new method which is a get request end def create #create method which is a post request end end 

每当我提交表单时给出错误,即使我使用了url:articles_path,默认发布请求。 我保持着

 def create end 

在控制器中

更改:

 resources :article 

至:

 resources :articles #plural 

这样它将映射到:

 articles_path POST /articles(.:format) articles#create 

对于使用本教程的许多人来说,这种情况发生的原因是他们在更改form_for帮助器中的url选项后不会重新加载表单。

在尝试提交表单之前,请务必重新加载表单的新副本 (您需要表单以获取最新的表单提交URL)。

您在控制器中的操作/方法什么也不做。 它应该是这样的:

 class ArticlesController < ApplicationController def new @article = Article.new end def create @article = Article.new(article_params) if @article.save redirect_to @article else render 'new' end end private def article_params params.require(:article).permit()# here go you parameters for an article end end 

在视图中:

 <%= form_for @article do |f| %> 

我更改了app / views / articles / new.html.erb:

<%= form_for :article do |f| %>

至:

<%= form_for :article, url: articles_path do |f| %>

RedZagogulin的回答是正确的 – 这是您需要在articles控制器中使用的代码

路线

您的问题的线索在这里:

 No route matches [POST] "/articles/new" 

通常,在使用正确的路由结构时 :

 #config/routes.rb resources :articles #-> needs to be controller name 

您会发现new操作是GET ,而不是POST 。 这让我相信你的系统设置不正确(它试图将表单数据发送到articles/new ,当它应该发送到[POST] articles

在此处输入图像描述

如果您按照RedZagogulin概述的步骤,它应该适合您

我不断遇到这个问题,结果是我的导航栏中有以下代码:

 <%= link_to "Blog", controller: 'articles' %> 

我切换到这一切,它开始工作:

 <%= link_to "Blog", articles_path %> 

我仍然是新手,所以不同的做事方式有时会让人感到困惑。

您可以在官方指南中找到答案。

因为此路线会转到您当前正在访问的页面,并且该路径仅用于显示新文章的表单。

编辑app / views / articles / new.html.erb中的form_with行,如下所示:

 <%= form_with scope: :article, url: articles_path, local: true do |form| %>