【问题标题】:authorizing specific controller action using cancancan使用 cancancan 授权特定的控制器操作
【发布时间】:2015-06-21 07:17:39
【问题描述】:

我有访问播放器 load_player 视图的链接以访问属于 current_user 的播放器。那么,我如何限制没有属于其他用户的俱乐部或俱乐部的 current_user 对 load_player 方法的访问。注意我想限制对 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  

能力.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  

【问题讨论】:

    标签: ruby-on-rails-4.1 ruby-2.1 cancancan


    【解决方案1】:
    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)
    

    希望这能解决您的问题:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多