如何使用CanCanCan获得关系的许可?

问题描述 投票:0回答:1

在我的应用程序中,我有一个名为User的模型has_one Talent。

在CanCanCan我有这个能力:

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

我的页面由ProfilesController#show呈现。像这样:

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

好。我试图渲染一个方法:is_public返回false的配置文件。但页面正在正确呈现,而我期望用户因为规则而无法看到页面:

   can :read, Talent, is_public?: true

我在这里失踪了什么?

ruby-on-rails cancancan
1个回答
2
投票

如果我没记错的话,

can :read, Talent, is_public?: true

上面的^ is_public?预计将成为Cancancan的一个属性。

但是因为is_public?是一种自定义方法,那么您可以尝试以下方法吗?

can :read, Talent do |talent|
  talent.is_public?
end
© www.soinside.com 2019 - 2024. All rights reserved.