Rails - superclass mismatch

2019-06-21 20:20发布

问题:

Playing with Rails and controller inheritance.

I've created a controller called AdminController, with a child class called admin_user_controller placed in /app/controllers/admin/admin_user_controller.rb

This is my routes.rb

  namespace :admin do
    resources :admin_user # Have the admin manage them here.
  end

app/controllers/admin/admin_user_controller.rb

class AdminUserController < AdminController
  def index
    @users = User.all
  end
end

app/controllers/admin_controller.rb

class AdminController < ApplicationController

end

I have a user model which I will want to edit with admin privileges.

When I try to connect to: http://localhost:3000/admin/admin_user/

I receive this error:

superclass mismatch for class AdminUserController

回答1:

To complete what @Intrepidd said, you can wrap your class inside a module, so that the AdminUserController class doesn't inherit twice from ApplicationController, so a simple workaround would be :

module Admin
  class AdminUserController < AdminController
    def index
      @users = User.all
    end
  end
end


回答2:

This error shows up if you define two times the same class with different superclasses. Maybe try grepping class AdminUserController in your code so you're sure you're not defining it two times. Chances are there is a conflict with a file generated by Rails.



回答3:

I fixed it by creating a "Dashboard" controller and an "index" def. I then edited my routes.rb thusly:

Rails.application.routes.draw do



namespace :admin do
    get '', to: 'dashboard#index', as: '/'

    resources :posts
end



end