开发者

Rails 3 RoutingError: No route matches {:controller=>"user_sessions"}

I'll just try to outline this as high level as I can. I am trying to access http://localhost:3000/login

The error is:

No route matches {:controller=&g开发者_C百科t;"user_sessions"}

And it's erroring on this line in the new.html.erb file below:

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

The route in routes.rb is:

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

The user_sessions_controller.rb is:

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

And the actual view for the login page is as follows (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 %>

Thank you.


Using form_for(@user_session) alone will try to build out the path using a resource you have defined in your routes.rb. Which you currently don't have (I'm assuming, as you didn't mention it. Please correct if I'm wrong.).

A few ways to go..

Add a resource and limit to the ones you need

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

These will use the default routing namings, but you can custom that up as you need.


Match out the routes you need.

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

View

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜