ruby-on-rails – 使用rails_admin和rails_api

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 使用rails_admin和rails_api前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我最初将其发布为 an issue on rails_api GitHub,但现在由于不活动而在此发布.

我正在尝试将rails_admin与Rails 5 API应用程序一起使用.我添加了额外的ActionController模块,以至于我可以使用有效的rails_admin面板或工作API请求.问题似乎是rails_admin依赖于ActionView :: Layouts,后面包含导致API请求的问题.

的Gemfile:

gem 'rails','>= 5.0.0.beta3','< 5.1'
...
gem 'rack-pjax',github: 'afcapel/rack-pjax'
gem 'remotipart',github: 'mshibuya/remotipart'
gem 'kaminari',github: 'amatsuda/kaminari',branch: '0-17-stable'
gem 'rails_admin',github: 'sferik/rails_admin'

我将我的应用程序配置为使用ActionDispatch :: Flash:

module MyApp
  class Application < Rails::Application
    ...
    config.middleware.use ActionDispatch::Flash
  end
end

I configured extra modules for Rails API,ApplicationController:

class ApplicationController < ActionController::API
  include Knock::Authenticatable
  include Pundit

  # RailsAdmin support
  include AbstractController::Helpers
  include ActionController::Flash
  include ActionController::RequestForgeryProtection
  include ActionController::MimeResponds
  include ActionController::HttpAuthentication::Basic::ControllerMethods
  include ActionView::Layouts
end

通过这些更改,Rails管理仪表板似乎运行正常.但是,当我尝试访问应用程序中的JSON资源时,会引发以下错误

Error:
BookingsControllerTest#test_should_get_index:
ActionView::MissingTemplate: Missing template bookings/index,application/index with {:locale=>[:en],:formats=>[:json],:variants=>[],:handlers=>[:raw,:erb,:html,:builder,:ruby,:haml]}. Searched in:
  * "/Users/richard/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/bundler/gems/rails_admin-355dc80f8a20/app/views"

测试代码(也尝试添加格式:: json):

class BookingsControllerTest < ActionController::TestCase
  test 'should get index' do
    get :index

    assert_response :success
  end
end

这是控制器代码

class BookingsController < ApplicationController
  def index
    @bookings = find_bookings
    render json: @bookings,include: ['customer','client'],Meta: Meta
  end
end

这只发生在我在顶级ActionController :: API类中包含ActionView :: Layouts模块以支持Rails Admin之后.

解决方法

如果我是你,我会尝试隔离API和RailsAdmin控制器.我认为这必须奏效:
class ApplicationController < ActionController::API
  include Knock::Authenticatable
  include Pundit
end

class RailsAdminCustomController < ApplicationController
  # RailsAdmin support
  include AbstractController::Helpers
  include ActionController::Flash
  include ActionController::RequestForgeryProtection
  include ActionController::MimeResponds
  include ActionController::HttpAuthentication::Basic::ControllerMethods
  include ActionView::Layouts
end

在config / initializers / rails_admin.rb中

RailsAdmin.config do |config|
  # other config stuff ...
  config.parent_controller = '::RailsAdminCustomController'
end

只需检查RailsAdmin :: ApplicationController here和配置设置here.

猜你在找的Ruby相关文章