Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to have multiple seeds.rb files? Any kind of 'versioning' for seed data?

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

However, if we simply add it to the 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've already added seed data to seeds.rb for, say, TableOne ... how can we incrementally add seed data for TableTwo and TableThree at later stages of development?

I'd hoped I could simply create a NEW seeds_two.rb file and run rake db:seeds_two but that gave an error Don't know how to build task 'db:seeds_two'

So it looks like ONLY "seeds.rb" can be used - so how DO people maintain incremental additions to seed data?

like image 364
jpw Avatar asked Aug 20 '11 07:08

jpw


People also ask

What is seed rb file?

The seeds.rb file is where the seed data is stored, but you need to run the appropriate rake task to actually use the seed data. Using rake -T in your project directory shows information about following tasks: rake db:seed. Load the seed data from db/seeds.rb. rake db:setup.

What is seed rb in rails?

Rails seed files are a useful way of populating a database with the initial data needed for a Rails project. The Rails db/seeds. rb file contains plain Ruby code and can be run with the Rails-default rails db:seed task.


2 Answers

You can re-use the seed task, but make it idempotent.

To make the seed idempotent, simply check for the existence of the condition before executing a command. An example: do you want to create a new admin user?

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

instead of

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

However, seed should be used to populate your database when the project is created. If you want to perform complex data seeding durin the lifecycle of the app, simply create a new rake task, execute it then remove it.

like image 79
Simone Carletti Avatar answered Sep 21 '22 23:09

Simone Carletti


For those who have concerns about this question

We can have multiple seed files in db/seeds/ folder, and, we can write a rake task to run separate file as we desire to run

# 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

Then, in order to run specific seed file, you can just run

rake db:seed:seed_file_name

To run all the seeds file with order in that db/seeds folder, run below command

rake db:seed:all
like image 36
quyetdc Avatar answered Sep 19 '22 23:09

quyetdc