开发者

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!


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜