开发者

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.

How do people maintain incremental additions to seed data?


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.


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 the separate files as we desire to run

# 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

      # Now we will create multiple tasks by each file name inside db/seeds directory. 

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

    # This is for if you want to run all seeds inside db/seeds directory
    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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜