I wrote code to manage initial data registered with rails db:seed using CSV files, so I’ll introduce it.
What this article covers
- Enable running seed by specifying model name
- Split seed files into multiple files separate from db/seeds.rb
- Manage seed data with CSV files
- Also enable registration with rails db:seed
Add rake task to execute seed by specifying model name
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 seed files for each model
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
Create CSV files for each model
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.
Execution method
Execute by specifying model name
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
Batch execution with rails db:seed
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.