srlrs20020 srlrs20020 - 4 months ago 84
Ruby Question

Rails routing error No route matches [POST] "/"

Hi am I trying to set up a basic form for an Article and am getting the following error when I submit the form:

No route matches [POST] "/"


Here is the form (I know I can use form_for, but I am trying to do it without):

<form accept-charset="UTF-8" action="<% articles_path %>" method="post">

<input type="hidden" name="authenticity_token" value="<%= form_authenticity_token %>">
<input type="text" name="title" placeholder="title">
<input type="text" name="body" placeholder="body">
<input type="submit">

</form>


Here is my routes.rb:

Rails.application.routes.draw do


resource :articles, only: [:new, :create]
root to: 'articles#new'
end


Here are my routes:

articles_path POST /articles(.:format) articles#create
new_articles_path GET /articles/new(.:format) articles#new
root_path GET / articles#new


What I don't understand is that my form action is articles_path with a post method, and the application is looking for a Post request to the root route. Shouldn't it go to my articles_path POST route? The same thing happens when I submit the form from articles/new except it says no route POST for articles/new.

I checked other similar questions and the solution was always something to do with the form action, which I have right as far as I can tell, so I thought I'd ask my own.

Answer

You are missing an = in <% articles_path %>. Your <form> tag should be:

<form accept-charset="UTF-8" action="<%= articles_path %>" method="post">

Without the =, the HTML output would have contained action="", causing the form to post to the URL of the current page.