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

时间:2015-05-02 10:57:54

标签: ruby-on-rails-4 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

1 个答案:

答案 0 :(得分:1)

发生这种情况是因为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?方法。以下示例假定权限与create方法相同:

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