0

我收到此错误:

 NoMethodError in Sessions#login

Showing c:/Documents and Settings/OverDuka/Desktop/controle/controle/app/views/sessions/login.html.erb where line #5 raised:

undefined method `model_name' for NilClass:Class

Extracted source (around line #5):

2: <% if flash[:note]%>
3: <%= flash[:note] %>
4: <%end%>
5: <%=form_for @user do |f| %>
6: Nome: <%= f.text_field :name %>
7: Senha: <%= f.password_field :password %>
8: <%= f.submit %>

我做了一个简单的登录系统,但这不起作用,我的控制器是:

class SessionsController < ApplicationController


  def login
        @user = User.where(params[:name],params[:password]).first
     if @user
          session[:user_id] = @user.id
          flash[:note] = 'Voce esta logado.'
          redirect_to finances_url
     else
       flash[:note] = 'Falha no login.'
     end
  end

  def destroy
  end
end

我的路线是

  match 'login' => 'sessions#login', :as => :login
  resources :finances
4

1 回答 1

0

您的 @user 变量不正确,请为您的会话控制器尝试此操作。此外,将“has_secure_password”添加到您的用户模型

class SessionsController < ApplicationController
   def new
   end

  def create
     user = User.find_by_email(params[:email])
     if user && user.authenticate(params[:password])
        session[:user_id] = user.id
          redirect_to finances_url, notice: 'Voce esta logado.'
     else
         flash.now.alert = 'Falha no login.'
        render "new"
       end
    end

 def destroy
     session[:user_id] = nil
      redirect_to root_url, notice: "Logged out!"
  end

那么在你看来

<%= form_tag sessions_path do %>
   <div class="field">
     <%= label_tag :email %><br />
    <%= text_field_tag :email, params[:email] %>
 </div>
 <div class="field">
  <%= label_tag :password %><br />
   <%= password_field_tag :password %>
 </div>
  <div class="actions"><%= submit_tag "Log In" %></div>
  <% end %>

在您的路线中

   get 'login', to: 'sessions#new', as: 'login'
   get 'logout', to: 'sessions#destroy', as: 'logout'
  resources :sessions
于 2012-08-18T16:22:40.797 回答