Rails: Create Default root user through migration? Rake task?

I'm testing my app out on Heroku (which is f***ing amazing!) and I realized that I have no way of creating my root user.

I'm using Authlogic and rails_authorization_plugin.

Is there someway I can add a section to one of my migration files to add this user and assign it the role of root? Or can I do this through a rake task?

Any insight would be appreciated!

Here's a similar question: stackoverflow.com/questions/62201/…
hgmnz 13.10.2009 21:30:58
2 ОТВЕТА
РЕШЕНИЕ

You could certainly do it though a migration, and I've seen that as a recommended way to add necessary seed data to an application's database. Migrations are just ruby code, so it's quite simple. You can use all the ActiveRecord stuff you're used to and do something like:

class AddRootUser < ActiveRecord::Migration
  def self.up
    user = User.create!( :email => '...', :login => 'root', :password => '...' )
  end

  def self.down
    user = User.find_by_login( 'root' )
    user.destroy
  end
end

I've left out things you'd probably want to do like rescuing a failure to create the user, etc. Also, I haven't used AuthLogic so I don't know exactly how its user model works, but you should be able to figure it out from here.

Another common pattern is to have the down migration completely clear the table and have the up migration call the down migration before running. That's probably not what you want in this case, though.

5
13.10.2009 20:38:23
Awesome, thanks! Turns out Authlogic does all the "crypted password" mumbo-jumbo when it's saving the record, so I don't need to do anything special. Afterwards, just calling user.has_role 'root' assigns the user as root. RoR is great!
neezer 13.10.2009 20:54:25

You can either set up a rake task to bootstrap the user (and any other seed data). Heroku actually lets you run rake tasks: http://docs.heroku.com/rake

Or, as a one off, you can create the user locally and upload your database to heroku using heroku db:push. Docs here: http://docs.heroku.com/taps#import-push-to-heroku

Also, I suggest against a data only migrations. There is even a seed data rake task in Rails core. See the railscast and this post.

2
13.10.2009 21:35:48