Rails 3 RoutingError:没有路由匹配{:controller =>“user_sessions”}

时间:2011-05-22 04:35:43

标签: ruby-on-rails ruby-on-rails-3

我会尝试将此概述为尽可能高的水平。我正在尝试访问http://localhost:3000/login

错误是:

No route matches {:controller=>"user_sessions"}

在下面的new.html.erb文件中,这行出错了:

<%= form_for(@user_session) do |f| %>

routes.rb中的路由是:

match 'login' => 'user_sessions#new', :as => :login

user_sessions_controller.rb是:

class UserSessionsController < ApplicationController
  def new
    @user_session = UserSession.new
  end

  def create
    @user_session = UserSession.new(params[:user_session])
    if @user_session.save
      flash[:notice] = "Successfully logged in."
      redirect_to root_path
    else
      render :action => 'new'
    end
  end

  def destroy
    @user_session = UserSession.find
    @user_session.destroy
    flash[:notice] = "Successfully logged out."
    redirect_to root_path
  end
end

登录页面的实际视图如下(new.html.erb):

<h1>Login</h1>

<%= form_for(@user_session) do |f| %>
  <% if @user_session.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@user_session.errors.count, "error") %> prohibited this user from being saved:</h2>

      <ul>
      <% @user_session.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
  <p>
    <%= f.label :login %><br />
    <%= f.text_field :login %>
  </p>
  <p>
    <%= f.label :password %><br />
    <%= f.password_field :password %>
  </p>
  <p><%= f.submit "Submit" %></p>
<% end %>

谢谢。

1 个答案:

答案 0 :(得分:2)

单独使用form_for(@user_session)会尝试使用您在routes.rb中定义的资源构建路径。你现在没有的(我假设,你没有提到它。如果我错了,请纠正。)。

有几种方法可以......

添加资源并限制您需要的资源

resources :user_sessions, :only => [:create, :destroy]

这些将使用默认路由命名,但您可以根据需要自定义。


匹配您需要的路线。

match 'login' => 'user_sessions#create', :as => :post_login, :via => :post

查看

= form_for(@user_session), :url => post_login_path do |f|
...