2017-09-25 87 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