没有路由匹配 [POST] "/sessions/new";(运行中的导轨 4) [英] No route matches [POST] "/sessions/new" (rails 4 in action)

查看:48
本文介绍了没有路由匹配 [POST] "/sessions/new";(运行中的导轨 4)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注 Rails 4 In action 手册,但遇到以下错误:

I'm following the Rails 4 In action book and I'm running into the following error:

No route matches [POST] "/sessions/new" 

我不知道为什么,因为我已经按照教程做了一个 T.这让我相信教程本身是有缺陷的.无论如何,出于某种原因,它在应该发布到 session#create 时发布到 session#new.我做错了什么?

I'm not sure why, as I've followed the tutorial to a T. Which leaves me to believe the tutorial itself is flawed. Anyhow, for some reason it's posting to sessions#new when it should be posting to sessions#create. What am I doing wrong?

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

sessions/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"

推荐答案

你说得对,本书有错误.

You are correct there is an error in this book.

当你有一个标签表单

<%= form_for :signin, method: "POST" do |f| %>

如果 rails 不知道 :signin 是什么意思,那么它会简单地复制当前 url 并将表单提交到该 url(在本例中为 'sessions/new'),使用后置动词(无论您是否指定!)

If rails doesn't know what :signin means, then it will simply copy the current url and will submit the form to that url (in this case 'sessions/new'), using the post verb (whether you specify it or not!)

<form accept-charset="UTF-8" action="/sessions/new" method="post">
....

显然,这不一定是您想要的,因为您没有用于 post HTTP 动词的/sessions/new,我认为最简单的解决方案是指定路由

Obviously, that's not necessarily what you want because you don't have a /sessions/new for post HTTP verb, I think the easiest solution would be to specify a route

post "/signin", to: "sessions#create", as: "signin"

并在您的 form_for

and in your form_for

<%= form_for signin_path do |f| %>

这篇关于没有路由匹配 [POST] "/sessions/new";(运行中的导轨 4)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆