Rails:仅允许管理员用户使用 Devise 在 Rails 中创建新用户(无外部模块)

编程入门 行业动态 更新时间:2024-10-10 02:15:14
本文介绍了Rails:仅允许管理员用户使用 Devise 在 Rails 中创建新用户(无外部模块)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

目前,我的用户数据库有一个名为admin"的列,其值为布尔值,默认设置为 false.我有一个管理员用户被植入到数据库中.

Currently, my Users database has a column called "admin" with a boolean value and the default set to false. I have one admin user seeded into the database.

如何编写我的应用程序,以便是管理员的用户可以创建新用户,但不是的用户不能?(此外,用户应该仅由管理员创建)

How do write my application so that users who are the admin can create new users, but users who are not cannot? (Also, users should be created only by the admin)

在设计中似乎应该有一种简单的方法来做到这一点,而不涉及使用某些外部模块.然而,到目前为止,我还没有找到满意的答案.

It seems like there should be a simple way to do this in devise that does not involve using some external module. So far however, I have not been able to find a satisfactory answer.

我更有可能标记仅设计的解决方案.(一个简单的标准 MVC/Rails 解决方案加分项)但是,如果真的有更好的方法来做到这一点而不涉及 CanCan,我可能也接受这一点.

I would be more likely to mark the solution which is devise only. (One that is simply standard MVC/Rails solution a plus) However, if there really is a better way to do it that doesn't involve CanCan I may accept that too.

注意:

我已经搜索了一段时间,我发现了其他几个与这个问题非常相似的 stackoverflow 问题,但要么没有完全回答这个问题,要么使用其他非设计模块.(或两者兼而有之)

I have been searching around for a while and I've found several other stackoverflow questions that are very similar to this one, but either don't quite answer the question, or use other non-devise modules. (Or both)

推荐答案

要实现授权,使用控制器上的方法

正如@diego.greyrobot 所建议的

Exactly as suggested by @diego.greyrobot

class UsersController < ApplicationController before_filter :authorize_admin, only: :create def create # admins only end private # This should probably be abstracted to ApplicationController # as shown by diego.greyrobot def authorize_admin return unless !current_user.admin? redirect_to root_path, alert: 'Admins only!' end end

为了避免设计已经登录"的问题,定义一个新的路径来创建用户.

我们将简单地定义一个新路由来处理用户的创建,然后将表单指向该位置.这样,表单提交就不会通过设计控制器,因此您可以按照正常的 Rails 方式随意使用它.

We will simply define a new route to handle the creation of users and then point the form to that location. This way, the form submission does not pass through the devise controller so you can feel free to use it anywhere you want in the normal Rails way.

# routes.rb Rails.application.routes.draw do devise_for :users resources :users, except: :create # Name it however you want post 'create_user' => 'users#create', as: :create_user end # users/new.html.erb # notice the url argument <%= form_for User.new, url: create_user_path do |f| %> # The form content <% end %>

更多推荐

Rails:仅允许管理员用户使用 Devise 在 Rails 中创建新用户(无外部模块)

本文发布于:2023-11-28 18:04:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643416.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:用户   建新   模块   中创   管理员

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!