2015-08-13 57 views
0

你好我on Rails應用程序的紅寶石我建立了一個認證系統爲用戶支架。Rails-身份驗證ACCES之前用戶在頁面

會話控制器

class SessionsController < ApplicationController 
    def new 
    end 

    def create 
    user = User.find_by_email(params[:email]) 
    if !user.nil? && user.authenticate(params[:password]) 
     session[:user_id] == user.id 
     redirect_to root_url 
    else 
     render :new 
    end 
    end 

    def destroy 
    session[:user_id] == nil 
    redirect_to login_url 
    end 
end 

在登錄後,我重定向用戶稱爲根頁面:chat_room

聊天室控制器

class ChatRoomController < ApplicationController 

    before_action :authenticate_user 

    def index 
    @current_user = User.where(id: params[:user_id]).first 
    end 
end 

並在application_controller

class ApplicationController < ActionController::Base 
    # Prevent CSRF attacks by raising an exception. 
    # For APIs, you may want to use :null_session instead. 
    protect_from_forgery with: :exception 

    def authenticate_user 
    if session[:user_id] == nil 
     redirect_to login_path 
    end 
    end 

end 

但白衣這種方法的應用重定向我總是即使憑據是正確的登錄頁面。

有人可以幫助我嗎?

回答

3

修正錯別字:

==比較

=分配

def create 
    user = User.find_by_email(params[:email]) 
    if !user.nil? && user.authenticate(params[:password]) 
    session[:user_id] == user.id 
    redirect_to root_url 
    else 
    render :new 
    end 
end 

def destroy 
    session[:user_id] == nil 
    redirect_to login_url 
end 

應該是:

def create 
    user = User.find_by_email(params[:email]) 
    if !user.nil? && user.authenticate(params[:password]) 
    session[:user_id] **=** user.id 
    redirect_to root_url 
    else 
    render :new 
    end 
end 

def destroy 
    session[:user_id] = nil 
    redirect_to login_url 
end