2013-01-15 46 views
0

我的设计已在我的rails 3项目上安装和配置,并且我想让它只有管理员才能创建/编辑用户。我如何编辑设计控制器来完成此任务?只有管理员才能创建一个新用户

+2

您可能想签出https://github.com/stffn/declarative_authorization - 上面还有一个旧的railscast - http://railscasts.com/episodes/188-declarative-authorization – house9

回答

0

我已经对此进行了排序。我记得这是一个痛苦,但它确实有效。它需要CanCan

假设一个管理员在User模型与admin布尔定义:

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 "[email protected] 
    redirect_to users_path 
    else 
    render :action => 'edit' 
    end 
end 

路线.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 

应该这样做。

0

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

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

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

1

我建议使用CanCan

首先,你define abilities喜欢:read:create:update:destroy和使用类似它们分配给用户角色:

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

然后,你会check those abilities通过检查用户是否有权限通过使用类似if can? :create, User的创建/编辑用户。

相关问题