Rails:仅允许管理员用户在具有Devise的Rails中创建新用户(无外部模块) [英] Rails: Only allow admin user to create new users in Rails with Devise (No external modules)

查看:97
本文介绍了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解决方案而已。)但是,如果确实有一种更好的方法不涉及Can Can我也可以也可以接受。

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的已登录问题,请定义一条创建用户的新途径。

我们将简单地定义一个新的路由处理用户的创建,然后将表单指向该位置。这样,表单提交不会通过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 %>

这篇关于Rails:仅允许管理员用户在具有Devise的Rails中创建新用户(无外部模块)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆