【问题标题】:RoR: Why inheritance not working for controller?RoR:为什么继承不适用于控制器?
【发布时间】:2018-04-04 17:02:29
【问题描述】:

我的应用程序有以下控制器:

class Api::BaseApiController< ApplicationController
  before_action :parse_request, :authenticate_member_from_token!

  def index
    render nothing: true, status: 200
  end

  protected
    def authenticate_member_from_token!
      if !request.headers[:escambo_token]
        @member = Member.find_by_valid_token(:activate, request.headers['escambo_token'])
        if !@member
          render nothing: true, status: :unauthorized
        end
      end
    end

然后,我有另一个从该控制器继承的控制器:

class Api::CategoryController < Api::BaseApiController
  before_action :find_category, except: [:index]

  def index
    @category = Category.all
    puts(@category)
    render json: @category
  end

但是控制器允许没有令牌的请求。

编辑 1:由于某种原因,index 操作开始正常工作。但仍未对令牌进行验证。

EDIT 2:修复方法从privateprotected

【问题讨论】:

  • @SergioTulentsev 已经修复!谢谢。
  • 你确定它正在通过正确的方法吗?您可以将 breapoints 放在那里以确保它们被调用
  • @maxpleaner 我再次编辑了问题。
  • @olegario:所以你是说它没有输入authenticate_member_from_token!?你怎么知道的?是否输入parse_request
  • 如果authenticate_member_from_token! 没有被调用,那么上面的代码中缺少一些重要的东西。我认为没有理由不调用它。

标签: ruby-on-rails ruby inheritance


【解决方案1】:

如果令牌丢失或无效,您的代码需要呈现 :unauthorized。换句话说,你需要的代码是这样的:

def authenticate_member_from_token!
  unless Member.find_by_valid_token(:activate, request.headers['escambo_token'])
    render nothing: true, status: :unauthorized
  end
end

但是,使用此代码,您可能会发现自己在控制器中进行了双重渲染。一种更简洁的方法可能是引发异常,然后从中拯救并适当呈现 - 例如

EscamboTokenInvalid = Class.new(StandardError)
rescue_from EscamboTokenInvalid, with: :escambo_unauthorized

def authenticate_member_from_token!
  unless Member.find_by_valid_token(:activate, request.headers['escambo_token'])
    raise EscamboTokenInvalid
  end
end

def escambo_unauthorized
  render nothing: true, status: :unauthorized
end

【讨论】:

  • 这里没有双重渲染。如果 before_action 呈现(或重定向),则不执行操作。
  • 啊,很公平。 rails 的怪癖.....不过,引发异常是常见的做法,因此可以根据需要进行自定义处理。
猜你喜欢
  • 2010-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-18
  • 2011-10-14
相关资源
最近更新 更多