扩展用于Active Admin和devise_token_auth的Rails应用程序控制器

问题描述

我正在尝试在Rails api后端中同时实现devise_token_auth和Active Admin。

devise_token_auth FAQ上有非常清晰的说明,解释了如何一起实现这两个方法-它需要两个不同的Application Controller类。

# app/controllers/api_controller.rb
# API routes extend from this controller
class ApiController < ActionController::Base
  include DevisetokenAuth::Concerns::SetUserByToken
end

# app/controllers/application_controller.rb
# leave this for ActiveAdmin,and any other non-api routes
class ApplicationController < ActionController::Base
end

我的应用程序中同时拥有这两个控制器,但是我不知道如何从它们继承Active Admin和devise_token_auth的控制器。

我确定我在这里缺少一些基本知识,因为在我在StackOverflow上看到的所有答案中,似乎都假设我知道该怎么做。

有人可以帮忙吗?

编辑:

解决问题,因为我认为我不是第一次很清楚。现在,即使我也创建了ApiController,Active Admin和devise_token_auth都在使用ApplicationController。如何使devise_token_auth使用ApiController?

解决方法

您绝对可以使用单独的命名空间,这将使您的代码更整洁,组织更好。但是,这不是强制性的。您所需要做的就是在API的控制器中,扩展ApiController而不是ActionController::Base

例如,这是一个基本的API控制器,

class Api::V1::BaseController < ActionController::API
  include DeviseTokenAuth::Concerns::SetUserByToken
  include Pundit
end

和一个扩展它的样本控制器,并使用devise_token_auth作为结果。

class Api::V1::SampleController < Api::V1::BaseController
  def index
    render json: { success: true,email: current_user.email },status: :ok
  end
end

这是一个示例项目,具有单独的Web和API控制器https://github.com/anujmiddha/rails-api-web-sample

,

您可以在github上的devise_token_auth的自述文件中参考devise_token_auth demo example

您的案例和演示应用程序之间的主要区别在于,您将使用ApiController而不是ApplicationController。另外,您还必须向相应的模型添加devise_token_auth属性,例如,如果要与用户一起使用devise_token_auth,则必须将属性添加到users表和{ {1}}至before_action: authenticate_user!。)