【发布时间】:2016-08-17 07:59:15
【问题描述】:
我正在使用 Devise,我希望允许 Only Admins 创建新用户。我已经查看了This 的答案,但它看起来已经过时了。我已经尝试了很多可能的答案,但没有任何效果。我正在寻找一个详细的答案,因为我还是一个新手。
管理员在 users 表中被标记为布尔值我试图保持最小化。
【问题讨论】:
标签: ruby-on-rails devise cancancan
我正在使用 Devise,我希望允许 Only Admins 创建新用户。我已经查看了This 的答案,但它看起来已经过时了。我已经尝试了很多可能的答案,但没有任何效果。我正在寻找一个详细的答案,因为我还是一个新手。
管理员在 users 表中被标记为布尔值我试图保持最小化。
【问题讨论】:
标签: ruby-on-rails devise cancancan
您可以通过多种方式实现这一目标。我过去所做的是结合显示\隐藏视图中的链接和检查控制器中的用户。我假设您有一个包含用户详细信息的表单,您将提交给用户控制器。
我在下面使用的一个应用中包含了一个控制器。
我要做的第一件事是检查用户是否经过身份验证(我们为此使用 google,但如果您已经设置了设备,则不需要这个,并且可能有自己的身份验证)。如果您已登录,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
【讨论】: