Rails 4设计,如何登录时注册新用户?

时间:2013-07-23 14:08:16

标签: ruby-on-rails devise authorization roles

我想阻止非管理员注册,以便只有超级用户/管理员才能添加新用户。我怎样才能做到这一点?

我尝试按照此处提到的方法:Devise before filter that prevents access to “new_user_registration_path” unless user is signed-in但没有结果。

我已经安装了设计,cancan和rolify。此外,我也不希望任何人访问/users/sign_up页面并登录。只有管理员必须能够注册新用户。

由于设计安装,没有用户控制器。如果需要,请指导我制作一个。

routes.rb

FifthApp::Application.routes.draw do
  devise_for :users
  resources :qanotes
end

user.rb

class User < ActiveRecord::Base

  #resourcify :resources
  rolify

  has_many :qanotes

  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

end

当我尝试去登录页面时(仅在登录后),我继续被重定向到root,即localhost:3000。

2 个答案:

答案 0 :(得分:0)

从用户模型中删除默认设计模块中的regesterable关键字。比你应该添加自己的表单来创建新用户,因此你可以添加新用户。 希望它会有所帮助。感谢

答案 1 :(得分:0)

您可customize registration controller(例如registrations_controller.rb),您应该添加before_filter身份验证,而before_filter仅限管理员registrations_controller.rb看起来像:

class RegistrationsController < Devise::RegistrationsController
 before_filter :authenticate_user!
 before_filter :is_administratior?, only: [:new, :create]

 def new
   super
 end

 def create
   super
 end

 private

  def is_administratior?
  if user_signed_in? # if user signed
   if current_user.administrator? # if adminstrator return true
     true
   else
     redirect_to some_path
   end
  else
    redirect_to login_path
  end
end

请参阅my answer here about Devise/cancan redirect admin