2016-08-17 95 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

你現在得到什麼錯誤? –

相關問題