【发布时间】:2013-08-28 13:30:34
【问题描述】:
我正在使用 Devise 和 CanCan 进行用户身份验证和管理角色,从而限制某些用户访问我的 Rails 4 应用程序的某些部分。
我在更新用户时遇到了一些问题。更新工作正常,数据库中的用户对象得到更新,但我的用户会话在以下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
【问题讨论】:
标签: ruby-on-rails devise ruby-on-rails-4 cancan