我正在使用Devise和CanCan進行用戶身份驗證和管理角色,限制某些用戶訪問部分Rails 4應用程序。更新用戶時,爲什麼current_user會話變爲零?
我遇到了更新用戶的一些問題。更新工作正常,數據庫中的用戶對象得到更新,但我的用戶會話在以下redirect_to
我的用戶顯示操作中丟失。 current_user
變成nil
這意味着CanCan可以限制對用戶顯示操作的訪問。
爲什麼current_user
在更新之後變成nil
當這種情況不會發生在其他動作上(例如創建,銷燬等)?
這些都是我的用戶模型中的色器件設置:
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:login]
這是我users_controller.rb的更新方法:
class UsersController < ApplicationController
load_and_authorize_resource
before_filter :authenticate_user!
def update
@user = User.find(params[:id])
if params[:user][:password].blank?
params[:user].delete(:password)
end
respond_to do |format|
if @user.update_attributes(user_params)
format.html { redirect_to user_path, :notice => 'User was successfully updated.' }
format.json { head :ok }
else
format.html { render :action => "edit" }
format.json { render :json => @user.errors, :status => :unprocessable_entity }
end
end
end
end
這是我ability.rb文件:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if defined?(user.role_id)
if user.role? :admin, user.role_id
can :manage, :all
elsif user.role? :hauler, user.role_id
can :manage, [User,Trip,Invoice], user_id: user.id.to_s
else
can :create, :Trip
end
end
end
end
感謝TRH。重定向工作正常,如果我更新用戶而不更新密碼。那麼根據你所說的話,如果他/她更改了密碼,我需要將用戶登錄回來,對嗎? – asprotte
yes - 特別是'sign_in @user,:bypass => true' - 你可以在這裏看到更多信息:https://github.com/plataformatec/devise/wiki/How-To%3a-Allow-users-to-編輯他們的密碼 – trh
偉大的作品!謝謝trh! – asprotte