I wrote code to manage initial data registered with rails db:seed using CSV files, so I’ll introduce it.
Create lib/tasks/seed.rake as follows.
Dir.glob(File.join(Rails.root, 'db', 'seeds', '*.rb')).each do |file|
desc "Load the seed data from db/seeds/#{File.basename(file)}."
task "db:seed:#{File.basename(file).gsub(/\\..+$/, '')}" => :environment do
load(file)
end
end
Create a db/seeds directory and create seed files for each model under it.
For example, for the Tag model, create tag.rb. I unified the file naming convention with app/models/tag.rb.
db/seeds/tag.rb
require "csv"
CSV.foreach("db/seeds/csv/tag.csv", headers: true) do |row|
Tag.create(name: row[0], description: row[1])
end
First, create a csv directory under db/seeds/.
mkdir db/seeds/csv/
Next, prepare a CSV file appropriately and save it as db/seeds/csv/tag.csv.
For CSV file management, in my case I decided to manage them with Google Spreadsheets so that non-engineers can easily edit them, and export them to CSV files.
With the rake task created this time, you can execute by specifying the model name in the format rake db:seed:modelname as follows.
bundle exec rake db:seed:tag
Just require the model-specific seed files added above in db/seeds.rb.
db/seeds.rb
require "./db/seeds/tag.rb"
Now you can register in batches with the rails db:seed command.
That’s all from the Gemba where I wanted to manage initial data with CSV files and register them with rails db:seed.