2016-08-12 7 views
0

我有一個接觸器,加載並通過cancancan授權的資源:覆蓋慘慘方法,這引起了異常「未初始化的不斷接觸」

class ContactsController < ApplicationController 
    before_filter :authenticate_user! 
    load_and_authorize_resource 
end 

我的索引行爲沒有被調用,因爲跟資源,纔可以訪問在名爲MongoidContainer的名稱空間內。因此,在我的系統中訪問聯繫人的唯一方法是MongoidContainer :: Contact。因此,當cancancan嘗試加載資源,一個異常這裏提出:

module CanCan 
    class ControllerResource 
    ... 
    def resource_class 
     case @options[:class] 
     when false then name.to_sym 
     when nil then namespaced_name.to_s.camelize.constantize 
     when String then @options[:class].constantize 
     else @options[:class] 
     end 
    end 
    ... 
    end 
end 

我試圖重寫ContactsController這種方法,但覆蓋永遠不會被調用。該模塊很可能不包含在ApplicationController名稱空間中。我怎樣才能重寫這個方法?

我沒有看到說你可以傳遞類選項這樣其運作選項:

load_and_authorize_resource class: 'MongoidContainer::Contact' 

我只是真的很好奇,爲什麼該方法在這種情況下沒有被覆蓋。

回答

0

ControllerResource很可能不在控制器的層次結構中,因此在控制器中定義該方法不會執行任何操作。

這暗示在這個類的文件的代碼。請參閱https://github.com/ryanb/cancan/blob/4560928dc375f9b31de00381c98334eb6aabc4b9/lib/cancan/controller_resource.rb#L2

處理加載和授權控制器邏輯,以便我們不會使用非接口方法混亂所有控制器。

我不積極,但CanCan似乎添加了一個before_filter,然後委託給ControllerResource。

# https://github.com/ryanb/cancan/blob/4560928dc375f9b31de00381c98334eb6aabc4b9/lib/cancan/controller_additions.rb#L14-L15 
def load_and_authorize_resource(*args) 
    cancan_resource_class.add_before_filter(self, :load_and_authorize_resource, *args) 

# https://github.com/ryanb/cancan/blob/4560928dc375f9b31de00381c98334eb6aabc4b9/lib/cancan/controller_resource.rb#L9-L10 
controller_class.send(before_filter_method, options.slice(:only, :except, :if, :unless)) do |controller| 
    controller.class.cancan_resource_class.new(controller, resource_name, options.except(:only, :except, :if, :unless)).send(method)