Custom Seed Data Using Rake in Ruby on Rails
By default, Ruby on Rails has a mechanism for seeding data with the app/db/seeds.rb
file for the entire application.
But, sometimes we need to run spesific seed without running the entire seed application. In this case, we can solved it using custom rake to seed the data.
1. Create Rake File
# app/lib/tasks/custom_seed.rake# frozen_string_literal: truenamespace :db do
namespace :seed do
desc 'Load the custom seed data from
db/seeds/my_custom_filename_seed.rb'
task single: :environment do
filename = Dir[File.join(Rails.root, 'db', 'seeds', "#{ENV['SEED']}.rb")][0]
puts "Seeding #{filename}..."
load(filename) if File.exist?(filename)
end
end
end
2. Create Seed File
Now, we can create spesific file for seeding spesific data. For example, in this article we created file app/db/seeds/posts_seed.rb
for seeding data in model Post.
# app/db/seeds/posts_seed.rb# bundle exec rake db:seed:single SEED=posts_seedposts = [
{ name: 'Post 1', description: 'My post 1'},
{ name: 'Post 2', description: 'My post 2' },
{ name: 'Post 3', description: 'My post 3' }
]
posts.each do |post|
puts "Creating post #{post[:name]}"
Post.find_or_create_by(name: post[:name], description: post[:description])
end
3. Running Seed for Spesific File
After creating files in app/db/seeds/*.rb
, we can execute it with this command.
Format :
bundle exec rake db:seed:single SEED=my_custom_filename_seed
Note : you can replace
my_custom_filename_seed
using your filename inside folderapp/db/seeds/
Example :
bundle exec rake db:seed:single SEED=posts_seed
Thanks for reading 🍉 💻