arnekolja’s current stuff

use the web you must, li'll padawan! 
« Back to blog

Ruby on Rails: Migrating with default users using restful_authentication

Whenever your web application is going to offer user management, you might want to install at least a default admin user when creating your database. I searched the web for ideas to implement this and most of them come up with adding fixtures to your migrations. That's a really good one, of course, but I bet there is no way to dynamically hash your password using a fixture. I am using restful_authentication right now and this plugin does not only hash your password using SHA1, but adds a salt too. So a fixture is not what I wanted.

Instead I included the model itself in my migration, so the hashing and validation methods are used automatically. Hope this snippet is going to help others who are seeking for the same stuff. Let me know if it came in handy for you :-)

require 'app/models/user.rb'

class LoadDefaultUsers < ActiveRecord::Migration
def self.up
say "Trying to insert default user(s)..."
user = User.create( :login => 'admin', :password => 'password', :password_confirmation => 'password', :email => 'admin@site.com' )
unless user.errors.empty?
say "Could not create admin user, see errors below:"
user.errors.each do |e|
say e
end
else
say "Admin user created"
end
end

def self.down
User.delete_all
end
end

Loading mentions Retweet

Comments (0)

Leave a comment...

 
Got an account with one of these? Login here, or just enter your comment below.
Posterous-login    Connect    twitter