How to make first user became admin in Devise gem?

2019-04-13 02:08发布

问题:

I want to make first user became admin.

So I have string attribute admin and I need to make some before filter or override Devise registration controller. Something like:

if User.first?
  User.admin = "admin"
  User.save
end

Here is devise regitration action

 def new
  resource = build_resource({})
  respond_with resource
end

What would be the better way to do this ?

回答1:

Assuming your code is not running very often (only when running your app in production for the first time) I would simply write a Rake task that does this for you once instead of cluttering your application code.

Put this in your Rakefile

task :promote_admin => :environment do
  User.first.update_attribute('admin', 'admin')
end

This way you keep your code clean while still having a very easy way to promote the first user during installation.

If you want to promote the first user you simply run rake promote_admin from the console and the first User will be promoted to admin.



回答2:

A better way would be to have admin field as boolean. And add the following before_filter to your model.

class User < ActiveRecord::Base
  before_save :set_admin

  private
  def set_admin
    self.admin = User.count == 0
  end
end

For this to work perfectly, you can have the following in your migration file

create_table(:users) do |t|
  t.boolean :admin, null: false, default: false
  ...
end

This will make the first user admin. Also, when you delete all your users and then a new user registers, this new user will be admin.



回答3:

it didn't work for me i had to change it a bit like this:

class User < ActiveRecord::Base

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  after_create :set_admin

  private
  def set_admin
   if  User.count == 1
     User.first.update_attribute(:admin, true)
   else
     return true
   end
  end
end