Rails建议添加样本数据的方法

我有一个类似于下面的Rake脚本,但我想知道是否有更有效的方法来执行此操作,而不必删除数据库,运行所有迁移,重新设置数据库,然后添加示例数据?

namespace :db do desc 'Fill database with sample data' task populate: :environment do purge_database create_researchers create_organisations add_survey_groups_to_organisations add_members_to_survey_groups create_survey_responses_for_members end end def purge_database puts 'about to drop and recreate database' system('rake db:drop') puts 'database dropped' system('rake db:create') system('rake db:migrate') system('rake db:seed') puts 'Database recreated...' end def create_researchers 10.times do researcher = User.new researcher.email = Faker::Internet.email researcher.save! end end 

我建议让rake db:seed自给自足。 我的意思是,你应该能够多次运行它而不会造成任何损害,同时确保加载所需的任何样本数据。

因此,对于您的研究,db:seed任务应该执行以下操作:

 User.destroy_all 10.times do researcher = User.new researcher.email = Faker::Internet.email researcher.save! end 

您可以反复运行此操作,并确保您最终会有10个随机用户。

我认为这是为了发展。 在这种情况下,我不会把它放在db:seed中,因为它可能会在生产中运行。 但是你可以把它放在一个类似的rake任务中,你可以根据需要重新运行。

您不应该通过db:seed用数据填充数据库。 这不是种子文件的目的。

db:seed用于应用程序运行所需的初始数据。 它不是用于测试和/或开发目的。

我所做的是拥有一个填充样本数据的任务和另一个删除数据库,创建,迁移,种子和填充的任务。 很酷的是,它由其他任务组成,因此您无需在任何地方复制代码:

 # lib/tasks/sample_data.rake namespace :db do desc 'Drop, create, migrate, seed and populate sample data' task prepare: [:drop, :create, "schema:load", :seed, :populate_sample_data] do puts 'Ready to go!' end desc 'Populates the database with sample data' task populate_sample_data: :environment do 10.times { User.create!(email: Faker::Internet.email) } end end