How should I go about loading (or updating) a database for my RoR application? This is a "one time" operation, so coding it in the application seems strange.
Also, how do I 开发者_运维知识库access the database after the application is running, do the models files sit somewhere on my server, accesible for "read-only"?
Thanks.
You essentially can write a script to load data into the database from CSV files.
The following is an example how you can do that:
require 'rubygems'
require 'csv'
infile = "db/data/csv/my_data.csv" # location of the file
count = 0
CSV.open(infile, 'r') do |row|
col1 = row[1]
col2 = row[2]
obj = MyObject.new({ :col1 => col1, :col2 => col2 })
obj.save
count += 1
print '.' if (count % 10) == 0
end
puts
puts "Successfully loaded #{count} records into database!"
Then run the script using rails command line tool runner: rails runner db/scripts/csv_data_loader.rb
.
The seeds.rb
is where you put one-time initialization code. You can find it in the db
sub-directory. This might of interest too: Database seeding.
If your application is already in production, use migrations.
精彩评论