[英]Rails Routing Error: No route matches
我的表單操作未按正確的路線操作時出現問題。 我知道我的路徑一定做錯了什么,但是rails使這個變得很容易,所以我不知道為什么它一直試圖在'/'而不是user_path / / users上嘗試post方法
這是我的表格:
<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_for之類的Form Helper 。 我強烈建議您開始研究它們,以便您可以使用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 %>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.