我如何读取 rails 控制器操作中的实例变量以制定政策

how can I read instance variable in rails controller action to pundit policy

控制器显示动作

def show
   @batch = Batch.find(params[:id])
   @batch_id = @batch.id
   authorize @batch
end

权威政策

def show?
puts @batch_id
    if !current_user.nil? && (current_user.role?('Student')) ||  (current_user.role?('Administrator')) || (current_user.role?('SupportSpecialist')) || (current_user.role?('Instructor'))
      true
    else
      false
    end
  end

我在 puts @batch_id 时得到的结果为零,我如何才能在政策行动中获得该价值

您的控制器:

def show
  @batch = Batch.find(params[:id])
  @batch_id = @batch.id
  authorize @batch
end

您的策略文件可能是:

class BatchPolicy
  attr_reader :user, :record
 
  def initialize(user, record)
    @user = user
    @record = record
  end
     
  def show?
    true if record ...  // record will be equal @batch
  end  
end

如果你想要额外的上下文,那么你必须知道:

Pundit strongly encourages you to model your application in such a way that the only context you need for authorization is a user object and a domain model that you want to check authorization for. If you find yourself needing more context than that, consider whether you are authorizing the right domain model, maybe another domain model (or a wrapper around multiple domain models) can provide the context you need.

Pundit does not allow you to pass additional arguments to policies for precisely this reason.

There你可以从马口中了解一下