No route matches [POST] “/articles/new”

前端 未结 7 1637
余生分开走
余生分开走 2020-12-31 09:57

When I try to submit the form its giving me the error

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

the files are: new.html.erb
this file

相关标签:
7条回答
  • 2020-12-31 10:18

    I was continually running into this problem and it came down to the fact that I had the following code in my navbar:

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

    I switched to this and it all started working:

    <%= link_to "Blog", articles_path %>
    

    I'm still new to this so the different ways of doing things sometimes gets confusing.

    0 讨论(0)
  • 2020-12-31 10:27

    RedZagogulins answer is right - that is the code you need to use in your articles controller

    --

    Routes

    The clue to your problem is here:

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

    Typically, when using the correct routing structure:

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

    You'll find that the new action is GET, not POST. This leads me to believe your system is set up incorrectly (it's trying to send the form data to articles/new, when it should just send to [POST] articles

    enter image description here

    If you follow the steps outlined by RedZagogulin, it should work for you

    0 讨论(0)
  • 2020-12-31 10:34

    You can find the answer on the official guideline.

    Because this route goes to the very page that you're on right at the moment, and that route should only be used to display the form for a new article.

    Edit the form_with line inside app/views/articles/new.html.erb to look like this:

    <%= form_with scope: :article, url: articles_path, local: true do |form| %>
    
    0 讨论(0)
  • 2020-12-31 10:35

    The reason why this occurs for many people using this tutorial is that they don't reload the form after changing the url option in the form_for helper.

    Be sure to reload a fresh copy of the form before trying to submit it (you need the form to have the most recent form submission url).

    0 讨论(0)
  • 2020-12-31 10:37

    Your actions/methods in the controller do nothing. It should be something like:

    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
    

    In the view:

    <%= form_for @article do |f| %>
    
    0 讨论(0)
  • 2020-12-31 10:40

    I changed app/views/articles/new.html.erb from:

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

    to:

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

    0 讨论(0)
提交回复
热议问题