Pundit 如何在 Rails 中授权自定义创建的方法?

How to Authorized a custom created method in Rails by Pundit?

我在 rails 4

中创建了自定义方法
def duplicate    
    new_house = @house.amoeba_dup  
    respond_to do |format|
        if new_house.save        
           format.html { render action: 'new', notice: 'Category Attribute Added Successfully' }
        else
           format.html { render action: 'new' }        
        end
    end    
end

但是当我调用复制方法时它给出 Pundit::AuthorizationNotPerformedError

发生这种情况是因为 Pundit 检测到您的新控制器方法未检查授权。这通常是由控制器中的这样一行触发的:

after_action :verify_authorized

因此将您的新方法更改为:

def duplicate    
  new_house = @house.amoeba_dup
  authorize new_house
  respond_to do |format|
    if new_house.save        
      format.html { render action: 'new', notice: 'Category Attribute Added Successfully' }
    else
      format.html { render action: 'new' }        
    end
  end    
end

您还需要更新 house_policy.rb 以添加 duplicate? 方法。下面的示例假定权限与创建方法相同:

# policies/house_policy.rb
class HousePolicy < ApplicationPolicy
  def duplicate?
    create?
  end