我正在使用設計,我想允許只有管理員創建新的用戶。我已經回顧了This的答案,但看起來過時了。我已經嘗試了很多可能的答案,但沒有奏效。我正在尋找一個詳細的答案,因爲我還是一個新手。如何僅允許管理員創建新用戶?
管理員在用戶表中標記了布爾值我試圖保持最小。
我正在使用設計,我想允許只有管理員創建新的用戶。我已經回顧了This的答案,但看起來過時了。我已經嘗試了很多可能的答案,但沒有奏效。我正在尋找一個詳細的答案,因爲我還是一個新手。如何僅允許管理員創建新用戶?
管理員在用戶表中標記了布爾值我試圖保持最小。
您可以實現這種多種方式。我過去所做的是將視圖中的鏈接隱藏並在控制器中檢查用戶的組合。我假設你有一個用戶詳細信息表單,你將提交給用戶控制器。
我從下面的一個應用程序中包含了一個控制器。
我要做的第一件事就是檢查用戶是否已通過身份驗證(我們使用谷歌進行身份驗證,但是如果您已經設置了身份驗證,則不需要此操作並且可能擁有自己的身份驗證)。如果你已經登錄了,應該包含你的「角色」屬性,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
那麼做到這一點的最簡單的方法是將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
希望這是你在找什麼。如果沒有,請進一步的細節評論。
#
# 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
仍然無法正常工作,但一直說「你已經登錄」 – Opapadaia
你現在得到什麼錯誤? –
我已經添加了用戶參數我自己,它確實工作,我認爲它會繼承它從設計控制器,然後我意識到,這個類是繼承自應用程序控制器類。無論如何謝謝你。但您的答案尚未完成,respond_to缺少結束標記。編輯它以將其標記爲正確答案 – Opapadaia