ユーザー認証と特定のユーザーの Rails 4 アプリの一部へのアクセスを制限するロールの管理に Devise と CanCan を使用しています。
ユーザーの更新で問題が発生しました。更新は正常に機能し、データベース内のユーザー オブジェクトは正常に更新されますが、次redirect_to
のユーザー表示アクションでユーザー セッションが失われます。current_user
これはnil
、CanCan がユーザーの show アクションへのアクセスを制限することを意味します。
他のアクション (作成、破棄など) では発生しないのに、更新後に発生するのはcurrent_user
なぜですか?nil
これらは私のユーザーモデルのデバイス設定です:
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:login]
これは私の users_controller.rb の update メソッドです:
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