Question

I'm writing a custom rails_admin controller (Backend::ImagesController) which inherits from RailsAdmin::MainController.

I followed the steps in this answer, but I'm getting an undefined_method error when my view uses the route helper backend_image_path(@image).

The controller is defined under controllers/backend/images_controller.rb as:

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 ....

My routes are defined as:

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

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

And the output of rake routes is what I expect:

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

Finally, from rails console:

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

This controller worked flawlessly until I tried to integrate it in RA by having it extend RailsAdmin::MainController

I do not know why the route_helper is not accessible from the controller anymore....

Was it helpful?

Solution

Here is the solution I found.

My mistake was the namespace of my custom controller: although RA engine is mounted on /backend, its namespace is still RailsAdmin.

This means that to have a custom controller in my backend, I have to create the controller under namespace RailsAdmin, thus

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

The controller is defined under controllers/rails_admin/images_controller.rb and views are in views/rails_admin/images/

Routing

Having a custom RA controller, implies drawing new routes for the engine itself, thus my routes.rb becomes like this:

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

To access the new engine routes (e.g. images INDEX):

rails_admin.images_path

An important RA wiki page for routes is this one

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top