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

后端 未结 13 1663
隐瞒了意图╮
隐瞒了意图╮ 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:16

    This is my new favorite solution, using the populator and faker gems:

    http://railscasts.com/episodes/126-populating-a-database

    0 讨论(0)
  • 2020-12-04 06:20

    Some of the answers are outdated. Since Rails 2.3.4, there is a simple feature called Seed available in db/seed.rb :

    #db/seed.rb
    User.create( :name => 'default', :password => 'password' )
    Comment.create( :title => 'Title', :body => 'First post!' )
    

    It provides a new rake task that you can use after your migrations to load data :

    rake db:seed
    

    Seed.rb is a classic Ruby file, feel free to use any classic datastructure (array, hashes, etc.) and iterators to add your data :

    ["bryan", "bill", "tom"].each do |name|
      User.create(:name => name, :password => "password")
    end
    

    If you want to add data with UTF-8 characters (very common in French, Spanish, German, etc.), don't forget to add at the beginning of the file :

    # ruby encoding: utf-8
    

    This Railscast is a good introduction : http://railscasts.com/episodes/179-seed-data

    0 讨论(0)
  • 2020-12-04 06:21

    Great blog post on this: http://railspikes.com/2008/2/1/loading-seed-data

    I was using Jay's suggestions of a special set of fixtures, but quickly found myself creating data that wouldn't be possible using the models directly (unversioned entries when I was using acts_as_versioned)

    0 讨论(0)
  • 2020-12-04 06:22

    That Rake task can be provided by the db-populate plugin:

    http://github.com/joshknowles/db-populate/tree/master

    0 讨论(0)
  • 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.
    0 讨论(0)
  • 2020-12-04 06:26

    I guess the best option is number 3, mainly because that way there will be no default user which is a great way to render otherwise good security useless.

    0 讨论(0)
提交回复
热议问题