DanMark
DanMark

Reputation: 75

How to seed data during deployment?

During deployment (to a shared host), I'd like check whether certain data is stored in the database, if not I'd like to insert it during the deployment process. Anyone know how to do what I've described?

Upvotes: 1

Views: 2099

Answers (4)

Evan V
Evan V

Reputation: 1867

---DB SEED APPROACH---

There is a file called seed.rb in db directory (app_root/db/seeds.rb) where you can add seed data. Commented out instructions are available in the file (copied below).

# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
#   cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
#   Mayor.create(name: 'Emanuel', city: cities.first)

You can fill in with the records you want to add eg :

Users.create(
            :email=>"dummy", :pwd_hash=>"3x35zbb2...", 
            :pwd_salt=>'423x', :admin=>true
)

...and then run rake db:seed to add the records to your tables.

---EDITING MIGRATION APPROACH---

Simplest option (though db:seed is probably better) is to just run migration with seed data. Just had to do this. Needed a seed user with admin privileges because site has no sign up option. Migration file below:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :email
      t.string :password
      t.string :name
      t.boolean :admin
      t.integer :company_id

      t.timestamps
    end

    #create the seed user with admin priviledges
    User.create!(:email=>"[email protected]", :password=>"test", :name=>"Dummy", :admin=>true, :company_id=>0)

  end
end

Upvotes: 0

thecatwasnot
thecatwasnot

Reputation: 33

Check out rake db:seed

There's even a railscast: http://railscasts.com/episodes/179-seed-data

Upvotes: 2

JeffO
JeffO

Reputation: 8043

I don't know how much flexibility you have with your host regarding other databases (Don't know if you can create another database just for these values), but you can place these data in xml documents and then have a script to insert these values if they don't exist.

Upvotes: 0

Spyros
Spyros

Reputation: 48626

I personally like to use fixtures to populate my database, whether it's testing or not. Once you create them, you can just create a rake task to reset your db and populate it. I have this reset_db.rake task :

namespace :db do
  desc "Drop, create, migrate, seed the database and prepare the test database for rspec"
  task :reset_db => :environment do
    Rake::Task['db:drop'].invoke
    Rake::Task['db:create'].invoke
    Rake::Task['db:migrate'].invoke
    Rake::Task['db:fixtures:load'].invoke
    Rake::Task['db:test:prepare'].invoke
  end
end

in my /lib/tasks folder. I execute it with "rake db:reset_db".

Upvotes: 0

Related Questions