ruby-on-rails-4.1ruby-2.1cancancan

authorizing specific controller action using cancancan


I have link to access player's load_player view to access player that belongs to current_user. So how can i restrict access to load_player method for current_user that has no belonging club or club belonging to other user. Note I want restrict access to load_player page.

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  

Solution

  • 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)
    

    Hope this solve your problem :)