我正在关注Rails 4 In行动书,我遇到了以下错误:
No route matches [POST] "/sessions/new"
我不知道为什么,因为我已经按照教程去了T.这让我相信教程本身是有缺陷的。无论如何,出于某种原因,当它应该发布到会话#new时,它会发布到会话#new。我做错了什么?
sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.where(:name => params[:signin][:name]).first
if user && user.authenticate(params[:signin][:password])
session[:user_id] = user.id
flash[:notice] = "Signed in successfully."
redirect_to root_url
else
flash[:error] = "Sorry."
render :new
end
end
end
节/ new.html.erb
<h1>Sign in</h1>
<%= form_for :signin, method: "POST" do |f| %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<p>
<%= f.label :password %><br />
<%= f.password_field :password %>
</p>
<%= f.submit "Sign in" %>
<% end %>
的routes.rb
get "/signin", to: "sessions#new"
post "/signin", to: "sessions#create"
答案 0 :(得分:5)
你是对的,这本书有错误。
当您有标签表单
时<%= form_for :signin, method: "POST" do |f| %>
如果rails不知道:signin
的含义,那么它只会复制当前网址,并将表单提交给该网址(在这种情况下为&#39; sessions / new&#39;) ,使用post动词(无论你是否指定它!)
<form accept-charset="UTF-8" action="/sessions/new" method="post">
....
显然,这不一定是你想要的,因为你没有发布HTTP动词的/ sessions / new,我认为最简单的解决方案是指定一条路线
post "/signin", to: "sessions#create", as: "signin"
并在您的form_for
中<%= form_for signin_path do |f| %>