2017-09-25 78 views
1

讓我們想象一下我有一個類退出Ruby on Rails的控制方法從助手

class Test < ActiveRecord::Base 
    include AuthenticatorHelper 

    def test 
    authenticate_or_fail! 
    puts "If I fail, this should be unreachable" 
    end 
end 

module AuthenticationHelper 
    def authenticate_or_fail! 
    @user = User.find(params[:token]) 
    unless @user 
     render :json => {code: 401, :err => 'Unauthorized'} and return 
    end 
    end 
end 

我想要做的是要麼認證或用JSON味精回覆。但是,它顯然忽略我return語句由於嵌套,它總是會打印我的消息

如果我失敗了,這應該是不可達

回答

1

就問題

你可以將電話提取爲before_filter/before_action(基於Rails版本)。

class Test < ActiveRecord::Base 
    include AuthenticatorHelper 

    before_action :authenticate_or_fail! 

    def test 
    puts "If I fail, this should be unreachable" 
    end 
end 

有關詳細信息,請參閱the documentation

由於您的幫助器方法會在發生故障時呈現,所以rails會阻止調用test方法。您將不需要0​​部分,那麼只能從該方法返回,因此是NoOp。

除了這個問題,但也值得一提:

我不想鍼砭了的緣故吧。我只是想阻止OP後來運行到一系列的錯誤。

User.find(params[:token]) 

如果未找到記錄,將引發異常。因此,在無效標記的情況下,unless @user部分將不會被評估。您可以使用

User.find_by(id: params[:token]) 

改爲。

看起來像是它充當控制器的您的課程名爲Test,並繼承自ActiveRecord::Base。第一個是不尋常的,因爲TestsController會更像沿軌道,秒看起來明顯錯誤。控制器必須從ApplicationController繼承(這本身ActionController::Base繼承)

+0

'的ActiveRecord :: Base'沒有一個'before_action' – Stefan

+0

這是正確的@Stefan,這就是爲什麼我建議從'ApplicationController'繼承,而不是。我被「ActiveRecord :: Base」追蹤了,但是在顯示的上下文中使用它肯定是一個錯誤,所以我只是假設它必須按照描述來修復。 – ulferts