简体   繁体   中英

How to get a permission from a relationship using CanCanCan?

In my app I have a model called User that has_one Talent.

In CanCanCan I have this ability:

class Ability
  include CanCan::Ability
  def initialize(user)

  if user.nil? 
    can :read, User
    can :read, Talent, is_public?: true
  else
    can :read, Talent, is_public?: true
  end

My page is being rendered by the ProfilesController#show. Like this:

class ProfilesController < ApplicationController
  before_action :check_ability, except: [:show]
  def show

    @user = User.find(params[:id])
    authorize! :read, @user
    authorize! :read, @user.talent

    if current_user
      sent_connections = current_user.sent_connections
      connections  = sent_connections + current_user.all_connections
      @is_connected = !(connections.select { |c| c.user.id == @user.id }.empty?)
    end
    @top_5_photos = @user.top_5_photos
  end

Well. Im trying to render a profile that the method: is_public returns false. But the page is being rendered correctly, while I expected was that the user cant see the page because of the rule:

   can :read, Talent, is_public?: true

What Im missing here?

If I remember it correctly,

can :read, Talent, is_public?: true

^ is_public? above is expected to be an attribute by Cancancan.

But because is_public? is a custom method, then can you try the following instead?

can :read, Talent do |talent|
  talent.is_public?
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM