2014-09-22 123 views
-1

我真的很喜歡讓我的政策負責確保所有變量都被填充和有效的想法,所以我們不會得到任何nil:nilClass錯誤或類似錯誤。檢查變量存在與評論者

我認爲這將是很好的,以確保用戶已經上傳的文件使用策略:

這裏是我創建行動:

def create 
    file = params[:file][:uploaded_file] 
    authorize file 
    # removed for brevity 
end 

而這裏的政策:

class AssetPolicy < ApplicationPolicy 
    def initialize(current_user, record) 
     @current_user = current_user 
     @record = record 
    end 

    def create? 
     @record != nil   
    end 
end 

但是,我收到以下意外錯誤:

當文件爲零時:

Pundit::NotDefinedError in Admin::Browser::AssetsController#create 
unable to find policy NilClassPolicy for 

當文件不是零:

Pundit::NotDefinedError in Admin::Browser::AssetsController#create 
unable to find policy ArrayPolicy for [#<ActionDispatch::Http::UploadedFile:0x000000050a2af8] 

所以我應該怎麼檢查的東西與權威人士的存在呢?

回答

0

我在做這在我的控制器:

file = params[:file][:uploaded_file] 
raise Pundit::NotAuthorizedError if file == nil 

它工作正常,但我想這個邏輯是在我的策略層:/起初我以爲它可能沒有什麼意義語義,因爲這不是授權的事情,但是當你考慮它時確實有道理;如果用戶尚未上傳文件,則他們無權訪問創建操作。

無論如何,我想在我的策略層的這個邏輯。開放給所有的建議:)

0

專家的工作方式是看看你傳遞給它的對象的類,然後調用該策略。

按照pundit github授權將調用的東西等同於(假設@asset是資產類的):

raise "not authorized" unless AssetPolicy.new(current_user, @asset).create? 

因此,爲了避開這個問題,你可以在你的控制器做:

def create 
    file = params[:file][:uploaded_file] 
    raise Pundit::NotAuthorizedError unless AssetPolicy.new(current_user, file).create? 
    # removed for brevity 
end 
1

在你的config /初始化/ pundit.rb文件,你可以添加

rescue_from Pundit::NotDefinedError, with: :user_not_authorized