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

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

提交回复
热议问题