Ruby on Rails
HowToPopulateYourDbFromScript

The plan here was to fill my database with thousands of records, and to be able to blow it all away and do it again if I so desired, like some kind of wild, fecund gunman.

your_rails_app/lib/rez_data_loader.rb

(note: ‘rez’ is the secret codename of my rails prototype, but I mustn’t let anyone know that, or the jig is up.)

# require AR
require 'rubygems'
require 'active_record'

# Load your yml config from rails
db_config = YAML::load(File.open("../config/database.yml"))

# Connect to the database, for me I only want this script to 
# work in the development env..
ActiveRecord::Base.establish_connection(db_config['development'])

# Load your custom models that you created 
# using ./script/generate, back in the days of yore...
require '../app/models/market'

# Let's try manipulating the AR. This could be a loop if we wanted. 
# Or a lollipop. but you'd have to define your lollipop AR model first!
m = Market.new
m.name_en = "Scott's Market of Power'"
m.desc_en = "created using my data loader"
m.save

# Let's have a look at what Dr Frankenstein has created
p(m) 

and the (slightly massaged, for the wiki) output:

smac:~/Dev/Ruby/rez/lib smaclure$ ruby rez_data_loader.rb 
#<Market:0x12a4894 
@new_record_before_save=true, 
@new_record=false, 
@errors=#<ActiveRecord::Errors:0x12a16e4 
@base=#<Market:0x12a4894 ...>, @errors={}>, 
@attributes={"name_en"=>"Scott's Market of Power'", 
"latitude"=>nil, "desc_en"=>"created using my data loader", 
"country_id"=>nil, "desc_fr"=>nil, "name_fr"=>nil, "id"=>2, 
"longitude"=>nil}>
smac:~/Dev/Ruby/rez/lib smaclure$ IT'S ALIIIIIVE!

—ScottMaclure

This script is an example of accessing your Rails environment from a stand-alone Ruby script. You can read more about how to access your Rails environment from a script on the Environments page.

Keep an eye on your associations while using mock data in your development environment. If you properly setup your associations in your data script, make sure you test the cases when those associations haven’t been created. Switch to production mode once in a while with an empty database.

Another method

If you’d just like to run a script you’ve written use:

ruby script/runner "load('whatever.rb')"

—AlexStrand

category:Howto