2016-09-25 108 views
0

我有一個用戶模型,它使用設計進行身份驗證,也有一個管理員模型,它也使用Devise。 我希望管理員能夠通過管理員/用戶/ {user.id}/edit編輯用戶配置文件,但是我希望通過Devise Controllers完成此過程,因此我試圖從Users :: RegistrationsController繼承,如下所示:如何繼承設計控制器

class Administrators::UsersController < Users::RegistrationsController 
before_action :set_user, only: [:show,:edit,:update,:destroy] 
def index 
    @users=User.all 
end 
def show 
end 

def new 
    super 
end 

def update 
    @user.update(user_params) 
    redirect_to [:administrators,:users] 
end 

,但我得到了以下錯誤:

找不到制定的路徑映射 「/管理員/用戶」。這可能發生的原因有兩個:1)您忘記將您的路線包裹在範圍區塊內。例如:devise_scope:user do「/ some/route」=>「some_devise_controller」end 2)您正在測試繞過路由器的Devise控制器。如果是這樣,你可以明確告訴設計使用哪個映射:@ request.env [「devise.mapping」] = Devise.mappings [:user]

我試圖改變路線,但我仍然得到相同的錯誤。 你能幫我嗎?

回答

1

繼承自Devise::RegistrationsController從代碼重用的角度看,最初看起來似乎是一個好主意,但它確實不是一個好主意。

控制器的意圖是非常不同的 - Devise::RegistrationsController部分處理未驗證的用戶 - 而設計控制器是可怕的野獸,由於在Devise內建的靈活性。

相反,您應該設置一個普通的舊CRUD控制器,因爲手頭的任務並不是非常複雜,與Devise::RegistrationsController的一半以上的破壞相比並不復雜。

# config/routes.rb 
namespace :administrators do 
    resources :users 
end 

# app/controllers/administrators/base_controller.rb 
module Administrators 

    class AuthorizationError < StandardError; end 

    class BaseController 
    respond_to :html 
    before_action :authenticate_user! 

    # Replace with the lib of your choice such as Pundit or CanCanCan 
    before_action :authorize_user! 
    rescue_from AuthorizationError, with: :unauthorized 

    private 

     def authorize_user! 
     raise AuthorizationError and return unless current_user.admin? 
     end 

     def unauthorized 
     redirect_to new_session_path, alert: 'You are not authorized.' 
     end 
    end 
end 

class Administrators::UsersController < Administrators::BaseController 

    before_action :set_user, only: [:show,:edit,:update,:destroy] 

    def show 
    end 

    def index 
    @users = User.all 
    end 

    def new 
    @user = User.new 
    end 

    def create 
    @user = User.create(user_params) 
    respond_with(:administrators, @user) 
    end 

    def edit 
    end 

    def update 
    @user.update(user_params) 
    respond_with(:administrators, @user) 
    end 

    def destroy 
    @user.destroy 
    respond_with(:administrators, @user) 
    end 

    private 

    def user_params 
     params.require(:user).permit(:email, :password, :password_confirmation) 
    end 
end 

相反,你可能希望把重點放在通過諧音例如重新使用的意見。

參見: