prepopulating admin user in database with authlogi

2019-05-06 10:07发布

问题:

I've been using the Authlogic rails plugin. Really all I am using it for is to have one admin user who can edit the site. It's not a site where people sign up accounts. I'm going to end up making the create user method restricted by an already logged in user, but of course, when I clear the DB I can't create a user, so I have to prepopulate it somehow. I tried just making a migration to put a dump of a user I created but that doesn't work and seems pretty hacky. What's the best way to handle this? It's tricky since the passwords get hashed, so I feel like I have to create one and then pull out the hashed entries...

回答1:

Rails 2.3.4 adds a new feature to seed databases.

You can add in your seed in db/seed.rb file:

User.create(:username => "admin", :password => "notthis", :password_confirmation => "notthis", :email => "admin@example.com")

Then insert it with:

rake db:seed

for production or test

RAILS_ENV="production" rake db:seed  
RAILS_ENV="test" rake db:seed

My favorite feature in 2.3.4 so far



回答2:

If you are using >= Rails 2.3.4 the new features include a db/seeds.rb file. This is now the default file for seeding data.

In there you can simple use your models like User.create(:login=>"admin", :etc => :etc) to create your data.

With this approach rake db:setup will also seed the data as will rake db:seed if you already have the DB.

In older projects I've sometimes used a fixture (remeber to change the password straight away) with something like users.yml:

admin:
  id: 1
  email: admin@domain.com
  login: admin
  crypted_password: a4a4e4809f0a285e76bb6b35f97c9323e912adca
  salt: 7e8455432de1ab5f3fE0e724b1e71500a29ab5ca
  created_at: <%= Time.now.to_s :db %>
  updated_at: <%= Time.now.to_s :db %>

rake db:fixtures:load FIXTURES=users

Or finally as the other guys have said you have the rake task option, hope that helps.



回答3:

Most used approach is to have a rake task that is run after deployment to host with empty database.



回答4:

Add a rake task:

  # Add whatever fields you validate in user model
  # for me only username and password
  desc  'Add Admin: rake add_admin username=some_admin password=some_pass'
  task :add_admin => :environment do
    User.create!(:username=> ENV["username"], :password=> ENV["password"],:password_confirmation => ENV["password"])
  end