只允许管理员用户在具有Devise(无外部模块)的Rails中创建新用户

编程入门 行业动态 更新时间:2024-10-10 06:17:36
本文介绍了只允许管理员用户在具有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解决方案a plus)但是,如果真的有一个更好的方式来做,不涉及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

为了回避Devise已经登录的问题,请定义创建用户的新路线。

我们将简单地定义一个新的路由来处理用户的创建,然后将表单指向该位置。这样,表单提交不会通过设计控制器,所以您可以随意使用它以正常的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 %>

更多推荐

只允许管理员用户在具有Devise(无外部模块)的Rails中创建新用户

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

发布评论

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

>www.elefans.com

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