只有管​​理员才能创建新用户

时间:2013-01-15 04:30:44

标签: ruby-on-rails ruby-on-rails-3 devise

我已经在我的rails 3项目上安装和配置了设计,我想让它只有管理员才能创建/编辑用户。如何编辑设计控制器来实现这一目标?

3 个答案:

答案 0 :(得分:1)

我建议使用CanCan

首先,您define abilities:read:create:update:destroy,并通过以下方式将其分配给用户角色:

if user.admin?
  can :manage, :all
end

然后,您将check those abilities检查用户是否有权使用if can? :create, User之类的内容创建/修改用户。

答案 1 :(得分:0)

如果您只需要允许管理员创建用户,您可以编写类似

的内容
class uUsersController < ApplicationController
  def create
     #validate if the current user is an admin 
  end
end 

更标准,更灵活的方式是使用像cancan这样的宝石,我个人更喜欢这样:)

答案 2 :(得分:0)

我之前已对此进行了整理。我记得这是一种痛苦,但确实有效。它需要CanCan

鉴于管理员在admin模型上定义了User布尔值:

<强> user.rb:

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable

  attr_accessor :current_password
  attr_accessible :name, :password, :password_confirmation, :current_password, :email, :remember_me, :admin

end

class Ability
    include CanCan::Ability

    def initialize(user)
    can :manage, :all if user.admin
  end
end

<强> users_controller.rb

def update
  @user = User.find(params[:id])
  params[:user].delete(:password) if params[:user][:password].blank?
  params[:user].delete(:password_confirmation) if params[:user][:password].blank? and params[:user][:password_confirmation].blank?
  if @user.update_attributes(params[:user])
    flash[:notice] = "Successfully updated "+@user.name
    redirect_to users_path
  else
    render :action => 'edit'
  end
end

<强>的routes.rb

devise_for :users, :path => "d"

devise_scope :user do
  get '/sign_in' => 'devise/sessions#new'
  get '/sign_out' => 'devise/sessions#destroy'
end

resources :users, :controller => "users"

<强> application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery

  after_filter :user_activity

  rescue_from CanCan::AccessDenied do |exception|
    redirect_to root_path
  end

  def admin?
    self.admin == true
  end

  def authenticate_admin
    redirect_to :new_user_session_path unless current_user && current_user.admin?
  end

  private

  def user_activity
    current_user.try :touch
  end

end

<强> application_helper.rb

def resource_name
  :user
end

def resource
  @resource ||= User.new
end

def devise_mapping
  @devise_mapping ||= Devise.mappings[:user]
end

应该这样做。