Is there a way to have multiple seeds.rb files? Any type of "version" for these seeds?

We need to add more seed data for some of the added tables to the "version 100" of our rails project.

However, if we simply add it to seeds.rb and re-run the rake db: seed command, it will, of course, RE-add the original seed data, duplicating it.

So, if you have already added seed data to the seeds.rb file, say, TableOne ... how can we gradually add seed data for TableTwo and TableThree at later stages of development?

I was hoping I could just create the NEW seed_two.rb file and run rake db:seeds_two, but that gave an errorDon't know how to build task 'db:seeds_two'

So, it looks like you can use ONLY "seeds.rb" - so how do people support incremental additions to the source data?

+6
source share
2 answers

You can reuse the task seed, but make it idempotent .

To make the seed idempotent, just check for the condition before executing the command. Example: Do you want to create a new admin user?

User.find_or_create_by_username(:username => "admin")

instead

User.create(:username => "admin")

However, seedit should be used to populate the database when creating the project. If you want to run a complex durin series of application life cycle data, just create a new rake task, execute it, then delete.

+11
source

For those who are concerned about this issue

db/seeds/ seed db/seeds/, rake ,

# lib/tasks/custom_seed.rake
# lib/tasks/custom_seed.rake
namespace :db do
  namespace :seed do

    Dir[File.join(Rails.root, 'db', 'seeds', '*.rb')].each do |filename|
      task_name = File.basename(filename, '.rb').intern

      task task_name => :environment do
        load(filename)
      end
    end

    task :all => :environment do
      Dir[File.join(Rails.root, 'db', 'seeds', '*.rb')].sort.each do |filename|
        load(filename)
      end
    end

  end
end

, ,

rake db:seed:seed_file_name

seed db/seeds seed,

rake db:seed:all
0

All Articles