简体   繁体   English

Rails:通过迁移创建默认的root用户吗? 耙任务?

[英]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. 我正在Heroku上测试我的应用程序(真是太神奇了!),我意识到我无法创建我的root用户。

I'm using Authlogic and rails_authorization_plugin. 我正在使用Authlogic和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 ? 是否可以以某种方式在我的迁移文件中添加一个部分来添加此用户并为其分配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: 您可以使用以前使用过的所有ActiveRecord东西,并执行以下操作:

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. 我遗漏了您可能想要做的事情,例如挽救了创建用户失败的工作,等等。而且,我没有使用AuthLogic,所以我不知道它的用户模型是如何工作的,但是您应该能够从这里找出来。

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). 您可以设置一个rake任务来引导用户(以及任何其他种子数据)。 Heroku actually lets you run rake tasks: http://docs.heroku.com/rake Heroku实际上允许您运行rake任务: 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 . 或者,可以一次性在本地创建用户,然后使用heroku db:push将数据库上传到heroku。 Docs here: http://docs.heroku.com/taps#import-push-to-heroku 此处的文档: 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. Rails核心甚至有一个种子数据耙任务。 See the railscast and this post . 参见railscast这篇文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM