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

I will just try to describe it as high as possible. I am trying to access http: // localhost: 3000 / login

Error:

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

And this is the error in this line in the new.html.erb file below:

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

Route in .rb routes:

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

User 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

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.

+3
source share
1 answer

Using only form_for(@user_session), you will try to build the path using the resource that you defined in routes.rb. Who you don’t have (I assume that you did not mention this. Please correct if I am wrong.).

A few ways to go.

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|
...
+2

All Articles