Populating the database with seeds.rb
Seed is data which is inserted into database for test.
db/seeds.rb is script for it.
Ruby 1.9
You need magic comment
# -*- encoding: UTF-8 -*-
Prepare example
seeds.rb is ruby script. You add ruby model creation codes.
Example
Simple database Item name:string quantity:integer
Item.create(name:'Madoka' quantity:1) Item.create(name:'Homuhomu' quantity:20) Item.create(name:'QB' quantity:100)
Cool insert
list = [["Madoka", 1], ["Homuhomu", 20],["QB", 100]] list.each_do |name,quantity| Item.create(name:name,quantity:quantity) end
Insert seed data
seed operations are rake command
rake db:setup
seeds.rb runs
This command includes rake db:create, rake db:schema:load, rake db:seed
just insert data
rake db:seed
Redo seed
rake db:reset
If you change database schema, you need to reset.
This command drops database and recreate(but no schema change, change is migration)
Seed according to env
We need env type seed operations. If possible, we separate seed data between production and development.
Create seeds folder
db/seeds, And create env folders development, production, etc…
improved seeds.rb
This script works with each env folder script
table_names = %w(users homuhomus madokas) # table name table_names.each do |table_name| path = Rails.root.join("db", "seeds", Rails.env, "#{table_name}.rb") if File.exist?(path) puts "Seeding #{table_name}..." require(path) end end
Get each table data and run each script