使用 Cancancan 授权特定的控制器操作



我有访问玩家load_player视图的链接,以访问属于current_user的播放器。那么,我如何限制没有属于俱乐部或属于其他用户的俱乐部current_user对load_player方法的访问。注意:我想限制对load_player页面的访问。

路线.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)

希望这可以解决您的问题:)

最新更新