Rails Routing Error: No route matches

Rails Routing Error: No route matches

有一个问题,我的表单操作没有达到正确的路线。我知道我一定是在路径上做错了,但是 rails 使这很容易,所以我不知道为什么它一直试图在 '/' 而不是 [=33] 上点击 post 方法=] 即 /users

这是我的表格:

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

这里是 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

这里是 routes.rb:

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

这里是 rake routes 输出:

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

最后是错误:

Routing Error  No route matches [POST] "/"

这是我的目录结构:

├── 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

要解决您当前的问题,请替换为:

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

与:

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

有关详细信息,请参阅 ActionView::Helpers::FormHelper

另外,如果你想使用 users_path 辅助方法,那么你应该在 <%= 中调用它,但是,而不是:<%。所以,你也可以试试这个:

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

然而,虽然这可以按照您想要的方式工作,但由于您正在使用 Rails,因此您应该使用 Form Helpers like form_for。我强烈建议您开始研究它们,以便您可以使用 Rails :)

的强大功能编写更好的代码

对于您的表单,您应该像这样构建它:

<%= 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 %>