How (and whether) to populate rails application with initial data

后端 未结 13 1714
隐瞒了意图╮
隐瞒了意图╮ 2020-12-04 05:43

I\'ve got a rails application where users have to log in. Therefore in order for the application to be usable, there must be one initial user in the system for the first pe

13条回答
  •  遥遥无期
    2020-12-04 06:25

    Try a rake task. For example:

    1. Create the file /lib/tasks/bootstrap.rake
    2. In the file, add a task to create your default user:
    
        namespace :bootstrap do
          desc "Add the default user"
          task :default_user => :environment do
            User.create( :name => 'default', :password => 'password' )
          end
    
          desc "Create the default comment"
          task :default_comment => :environment do
            Comment.create( :title => 'Title', :body => 'First post!' )
          end
    
          desc "Run all bootstrapping tasks"
          task :all => [:default_user, :default_comment]
        end
    
    1. Then, when you're setting up your app for the first time, you can do rake db:migrate OR rake db:schema:load, and then do rake bootstrap:all.

提交回复
热议问题