【问题标题】:Getting Routing Error while submit the form using ROR使用 ROR 提交表单时出现路由错误
【发布时间】:2016-06-04 09:37:47
【问题描述】:

我需要一个帮助。使用 ROR 发布表单数据时出现以下错误。

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

Rails.root: C:/Sites/blog
Application Trace | Framework Trace | Full Trace

Routes

Routes match in priority from top to bottom
Helper  HTTP Verb   Path    Controller#Action
Path / Url          
articles_path   GET     /articles(.:format)     articles#index
    POST    /articles(.:format)     articles#create
new_article_path    GET     /articles/new(.:format)     articles#new
edit_article_path   GET     /articles/:id/edit(.:format)    articles#edit
article_path    GET     /articles/:id(.:format)     articles#show
    PATCH   /articles/:id(.:format)     articles#up

我在下面解释我的代码。

new.html.erb:

<%= form_for @article do |f| %>
  <p>
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </p>

  <p>
    <%= f.label :text %><br>
    <%= f.text_area :text %>
  </p>

  <p>
    <%= f.submit %>
  </p>
<% end %>

date 

当用户提交此表单时,会出现此类错误。我的route.rb 文件如下所示。

Rails.application.routes.draw do
  resources :articles
  root 'welcome#index'
end

我的控制器文件代码如下。

class ArticlesController < ApplicationController
    def new

    end
    def create
        @article = Article.new(article_params)
    if @article.save
      redirect_to @article
    else
      render 'new'
    end
    end
end

我使用的是 Rails 版本4.2...。请帮我解决这个错误。

【问题讨论】:

  • Rails 默认的new 操作是GET /articles/new,但默认的create 操作是POST /articles(最后没有/new);您的表单被提交到错误的 URL。顺便说一句,你的def new控制器方法不应该包含@article = Article.new吗?
  • 你能编辑你的答案吗?

标签: ruby forms ruby-on-rails-4


【解决方案1】:

默认的 Rails new 操作是 GET /articles/new,但默认的 create 操作是 POST /articles(最后没有 /new);您的表单以某种方式提交到了错误的 URL。

为了快速重新创建这个场景,我在终端中输入了以下内容:

rails new blog
cd blog
rails generate scaffold articles
rake db:migrate
rails s

... 它使用以下 def new 方法创建了一个 Articles 控制器:

# GET /articles/new
def new
  @article = Article.new
end

我在浏览器中导航到http://127.0.0.1:3000/articles,然后单击“新建文章”,然后单击“创建文章”;没有发生错误。

但是,从 def new 中删除 @article = Article.new 行(以匹配您问题中的控制器代码)导致“新文章”页面上出现以下错误:

ArgumentError in Articles#new

First argument in form cannot contain nil or be empty

Extracted source (around line #1): <%= form_for(@article) do |f| %>

我不确定您是如何做到足够远以看到 No route matches [POST] "/articles/new" 消息的,但我想缺少的 @article = Article.new 行与它有关。

【讨论】:

    【解决方案2】:

    您可以通过添加:

    def new
      @article = Article.new
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-18
      • 2018-01-27
      • 2011-07-28
      • 2014-02-25
      • 2018-11-24
      • 2017-08-24
      • 2011-01-06
      相关资源
      最近更新 更多