使用 cancancan 授权特定的控制器操作
authorizing specific controller action using cancancan
我有 link 访问玩家的 load_player 视图以访问属于 current_user 的玩家。那么,我如何限制 load_player 没有所属俱乐部或属于其他用户的俱乐部的 current_user 方法的访问权限。注意我想限制对 load_player 页面的访问。
routes.rb
get 'player/load_player/:id' => "player#load_player", as: :player
player_controller.rb
class PlayerController < ApplicationController
before_action :authenticate_user!
authorize_resource :class => false
layout "player"
def load_player
@club_hash = Club.where({:id => params[:id]}).pluck(:club_hash).first
end
end
ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.is?(:admin)
can :manage, :all
elsif user.is?(:owner)
can :read, all: { except: [UploadedSong]}
can :manage, Club, user_id: user.id
can :read, :load_player, id: user.id
elsif user.is?(:user)
can :read, all: { except: [UploadedSong]}
end
end
end
current_user.clubs.where(id: params[:id]).pluck(:club_hash).try(:first)
# or add user_id inside where clause
Club.where(id: params[:id], user_id: current_user.id).pluck(:club_hash).try(:first)
希望这能解决您的问题:)
我有 link 访问玩家的 load_player 视图以访问属于 current_user 的玩家。那么,我如何限制 load_player 没有所属俱乐部或属于其他用户的俱乐部的 current_user 方法的访问权限。注意我想限制对 load_player 页面的访问。
routes.rb
get 'player/load_player/:id' => "player#load_player", as: :player
player_controller.rb
class PlayerController < ApplicationController
before_action :authenticate_user!
authorize_resource :class => false
layout "player"
def load_player
@club_hash = Club.where({:id => params[:id]}).pluck(:club_hash).first
end
end
ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.is?(:admin)
can :manage, :all
elsif user.is?(:owner)
can :read, all: { except: [UploadedSong]}
can :manage, Club, user_id: user.id
can :read, :load_player, id: user.id
elsif user.is?(:user)
can :read, all: { except: [UploadedSong]}
end
end
end
current_user.clubs.where(id: params[:id]).pluck(:club_hash).try(:first)
# or add user_id inside where clause
Club.where(id: params[:id], user_id: current_user.id).pluck(:club_hash).try(:first)
希望这能解决您的问题:)