我最初将此发布为Rails_api GitHub 上的问题 https://github.com/sferik/rails_admin/issues/2617,但由于不活跃,我现在将其发布在这里。
我正在尝试使用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
我为 Rails API 配置了额外的模块 https://github.com/rails-api/rails-api#choosing-controller-modules,应用程序控制器:
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"
测试代码(也尝试添加format: :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
这仅在我包含之后才会发生ActionView::Layouts
顶层模块ActionController::API
支持 Rails Admin 的类。