2016-08-17 97 views
1

我正在使用设计,我想允许只有管理员创建新的用户。我已经回顾了This的答案,但看起来过时了。我已经尝试了很多可能的答案,但没有奏效。我正在寻找一个详细的答案,因为我还是一个新手。如何仅允许管理员创建新用户?

管理员在用户表中标记了布尔值我试图保持最小。

回答

1

您可以实现这种多种方式。我过去所做的是将视图中的链接隐藏并在控制器中检查用户的组合。我假设你有一个用户详细信息表单,你将提交给用户控制器。

我从下面的一个应用程序中包含了一个控制器。

我要做的第一件事就是检查用户是否已通过身份验证(我们使用谷歌进行身份验证,但是如果您已经设置了身份验证,则不需要此操作并且可能拥有自己的身份验证)。如果你已经登录了,应该包含你的“角色”属性,Devise将创建current_user对象。在标准用户创建中,您可以检查当前user.role,如果current_user.role不是1(我假设1表示管理员),只需重定向。

class UsersController < ApplicationController 

    # Set the user record before each action 
    before_action :set_user, only: [:show, :edit, :update, :destroy] 

    # User must authenticate to use all actions in the users controller 
    before_filter :authenticate_user! 

    def create 
    if current_user.role = 1 then 
     @user = User.new(user_params) 
     @user.password = Devise.friendly_token[0,20] 

     respond_to do |format| 
     if @user.save 
      format.html { redirect_to @user, notice: 'User was successfully created.' } 
      format.json { render action: 'show', status: :created, location: @user } 
     else 
      format.html { render action: 'new' } 
      format.json { render json: @user.errors, status: :unprocessable_entity } 
     end 
     end 
    else 
     format.html { redirect_to @user, notice: 'You do not have sufficient rights to set up a new user.' } 
    end 
    end 

    private 

    # Use callbacks to share common setup or constraints between actions. 
    def set_user 
    @user = User.find(params[:id]) 

    rescue ActiveRecord::RecordNotFound 
    flash[:notice] = "User record does not exist" 
    redirect_to users_url 
    end 
end 
+0

我已经添加了用户参数我自己,它确实工作,我认为它会继承它从设计控制器,然后我意识到,这个类是继承自应用程序控制器类。无论如何谢谢你。但您的答案尚未完成,respond_to缺少结束标记。编辑它以将其标记为正确答案 – Opapadaia

1

那么做到这一点的最简单的方法是将before_action添加到您的用户控制器限制创建和编辑和任何其它行动要具体标准

before_action :create_user , only: [:edit , :update , :new, :correct_user] 

,然后你可以定义创建用户私有方法

def create_user 

    @user=User.find(params[:id]) 
    redirect_to @user unless @user.criteria == criteria 
    end 

希望这是你在找什么。如果没有,请进一步的细节评论。

+0

但设计没有用户控制器 – Opapadaia

+0

这可能会帮助您找到控制器的位置。 http://stackoverflow.com/questions/6234045/how-do-you-access-devise-controllers –

+0

每当我点击link_to创建新用户,它返回一个错误消息“您已经登录” – Opapadaia

1
# 
# In Users_Controller 
# 
before_action :check_user_role , only: [:edit , :update , :new, :create] 

def check_user_role 
    redirect_to home_path if current_user.role != "Your Role" 
end 
+0

仍然无法正常工作,但一直说“你已经登录” – Opapadaia

+0

你现在得到什么错误? –

相关问题