2015-11-04 108 views
1

遇到我的表單操作未達到正確路由的問題。我知道我必須在路徑上做一些錯誤的事情,但是rails會讓這很容易,所以我不知道爲什麼它會一直嘗試使用'/'而不是user_path,它是/ 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 
+0

試試這樣說:'<形式action =「/ users」method =「post」>'? –

+1

謝謝你的工作。 – yoshinator

回答

1

爲了解決你目前的問題,更換此:

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

有了:

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

更多信息請參見ActionView::Helpers::FormHelper

另外,如果你想使用users_path幫手方法,那麼你應該調用<%=而不是:<%。所以,你可以試試這個太:

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

不過,雖然這工作你想要的方式,但因爲你是使用Rails,你應該利用Form Helpersform_for。我強烈建議你開始尋找到他們,這樣就可以使用Rails的力量:)

+1

謝謝!這工作如何我想要它。 – yoshinator

+0

很高興我能幫到你。雖然這種方式按照你想要的方式工作,但是當你使用Rails時,你應該使用Form Helper這樣的Form Helper。我強烈建議您開始研究它們,以便使用Rails的強大功能編寫更好的代碼:)祝您好運:) –

+1

謝謝我的朋友。非常感謝您的幫助。 – yoshinator

0

爲了您的表格,您應該構建像這樣寫更好的代碼:

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

謝謝。我愛表單助手。我在週末才發現他們。我需要開始執行我的練習題。 – yoshinator