2

我正在编写一个继承自 RailsAdmin::MainController 的自定义 rails_admin 控制器(Backend::ImagesController)。

我按照这个答案中的步骤进行操作,但是当我的视图使用路由帮助程序 backend_image_path(@image) 时出现 undefined_method 错误。

控制器在 controllers/backend/images_controller.rb 下定义为:

module Backend
  class ImagesController < RailsAdmin::MainController
    #layout 'rails_admin/cropper'

    skip_before_filter :get_model
    skip_before_filter :get_object
    skip_before_filter :check_for_cancel

    .... the various actions ....

我的路线定义为:

namespace 'backend' do
  resources :images do
    member do
      get :cropper
      post :crop
    end
  end
end

mount RailsAdmin::Engine => '/backend', :as => 'rails_admin'

rake 路由的输出是我所期望的:

backend_image GET  /backend/images/:id(.:format) backend/images#show {:protocol=>"https://"}

最后,从 rails 控制台:

app.backend_image_path(id: 10)
=> "/backend/images/10"

在我尝试通过扩展 RailsAdmin::MainController 将它集成到 RA 之前,这个控制器工作得非常完美

我不知道为什么不再可以从控制器访问 route_helper ....

4

1 回答 1

5

这是我找到的解决方案。

我的错误是我的自定义控制器的命名空间:虽然 RA 引擎安装在/backend上,但它的命名空间仍然是RailsAdmin

这意味着要在我的后端有一个自定义控制器,我必须在命名空间RailsAdmin下创建控制器,因此

module RailsAdmin
   class ImagesController < RailsAdmin::MainController     

       # unless your controller follows MainController routes logic, which is 
       # unlikely, these filters will not work 

       skip_before_filter :get_model
       skip_before_filter :get_object
       skip_before_filter :check_for_cancel

       ....
   end
end

控制器在controllers/rails_admin/images_controller.rb下定义,视图在views/rails_admin/images/

路由

拥有一个自定义的 RA 控制器,意味着为引擎本身绘制新的路由,因此我的 routes.rb 变成了这样:

RailsAdmin::Engine.routes.draw do
   # here you can define routes for the engine in the same way you do for your app

   # your backend must be under HTTPS
   scope protocol: 'https://', constraints: {protocol: 'https://'} do
      resources :images
   end
end

MyApp::Application.routes.draw do
   # your application's routes
   .....
end

要访问新的引擎路线(例如图像索引):

rails_admin.images_path

一个重要的 RA wiki 页面就是这个

于 2014-08-25T14:04:47.250 回答