如何使用Devise将注册限制为管理员

时间:2012-04-04 23:37:18

标签: ruby-on-rails ruby devise

我正在尝试将注册限制为Devise管理员。如果可能的话,我现在想避免使用CanCan。我已经创建了一个单独的Devise Admin模型,如选项#1中所述:https://github.com/plataformatec/devise/wiki/How-To:-Add-an-Admin-Role

接下来,我为用户设置了一个CRUD界面,如下所述:https://github.com/plataformatec/devise/wiki/How-To:-Manage-users-through-a-CRUD-interface

我想通过在Users控制器中使用类似before_filter :authenticate_admin!的内容来限制新注册,但出于某种原因,它并不限制新的注册。

我的routes.rb看起来像这样:

devise_for :admins
devise_for :users, :path_prefix => 'd'
resources :admins
resources :users, :controller => "users"

为什么before_filter :authenticate_admin!不限制新注册的任何想法?

3 个答案:

答案 0 :(得分:9)

您无法在用户控制器中使用before_filter :authenticate_admin!,因为管理员和用户是您应用中的两个不同型号。

我不知道我是否完全理解你的意思,但如果你不想接受用户(或管理员)的新注册,你可以这样做:

# in your User(Admin) model
devise :registerable # remove :registerable

希望这有帮助!

答案 1 :(得分:2)

我正在寻找类似的东西;完全禁用新注册。我在某个地方的邮件列表上挖了这个,虽然它解决了我的问题,但对你来说这可能是一个不错的起点:

class RegistrationsController < Devise::RegistrationsController 
  def new
    flash[:failure] = t('registrations.registrations_disabled')
    redirect_to root_path
  end
end

也许类似的东西,但添加一个检查,以查看current_user是否为管理员,然后根据该重定向......

答案 2 :(得分:1)

我思索了一段时间,终于想出了这个。

设计创建的每个模型都有一个辅助函数

class UsersController < Devise::RegistrationsController

  before_filter :authenticate_admin!

  def new
    if admin_signed_in?
      super
    else
      redirect_to admin_session_path
    end
   end

希望这会有所帮助。它就像一个魅力:)

相关问题