yoshinator
yoshinator

Reputation: 485

Rails Routing Error: No route matches

Having an issue where my form action is not hitting the right route. I know I must be doing something wrong with the path but rails makes this pretty easy so I don't know why it keeps trying to hit the post method on '/' instead of the user_path which is /users

Here is my form:

<form  action="<% users_path %>" method="post">
<input type="email" name="user[email]" placeholder="your email"/>
# other inputs and submit

Here is the users_controller.rb:

def create
   @user = User.new(user_params)
   if @user.save
      flash[:message] = @user.email +" Created succesfully!"
   else
      flash[:message] @user.errors.full_messages.to_sentence
   redirect_to root_path
end

and here is routes.rb:

root 'application#welcome'
post 'users' => 'users#create'

Here is rake routes output:

Prefix Verb URI Pattern      Controller#Action   
root   GET  /                application#welcome  
users  POST /users(.:format) users#create

and finally the error:

Routing Error  No route matches [POST] "/"

Here is my directory structure:

├── app
│   ├── assets
│   │   ├── images
│   │   ├── javascripts
│   │   │   ├── application.js
│   │   │   └── users.coffee
│   │   └── stylesheets
│   │       ├── application.css
│   │       └── users.scss
│   ├── controllers
│   │   ├── application_controller.rb
│   │   ├── concerns
│   │   └── users_controller.rb
│   ├── helpers
│   │   ├── application_helper.rb
│   │   └── users_helper.rb
│   ├── mailers
│   ├── models
│   │   ├── concerns
│   │   └── user.rb
│   └── views
│       ├── application
│       │   └── welcome.html.erb
│       ├── layouts
│       │   └── application.html.erb
│       └── users

Upvotes: 1

Views: 78

Answers (2)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34336

To solve you current problem, replace this:

<form action="<% users_path %>" method="post">

With:

<form action="/users" method="post">

See ActionView::Helpers::FormHelper for more information.

Also, if you want to use the users_path helper method, then you should call that inside a <%= But, not: <%. So, you can try this too:

<form action="<%= users_path %>" method="post">

However, although this works the way you want, but as you are using Rails, you should make use of the Form Helpers like form_for. I strongly suggest you to start looking into them so that you can write better code using the power of Rails :)

Upvotes: 1

DustinFisher
DustinFisher

Reputation: 396

For your form you should structure it like this:

<%= form_for(@user) do |f| %>
  <div class="field form-group">
    <%= f.label :email %><br />
      <%= f.text_field :email, class: 'form-control' %>
    </div>
    ....other fields etc....
    <div class="actions form-group">
      <%= f.submit "Create User", class: 'btn btn-primary' %>
    </div>
  </div>
<% end %>

Upvotes: 0

Related Questions