ruby-on-rails - Rails 推荐的添加示例数据的方法

标签 ruby-on-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 任务中,你可以根据需要经常重新运行。

关于ruby-on-rails - Rails 推荐的添加示例数据的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17580031/

相关文章:

javascript - 有没有办法在 ruby​​ 中的上传文件或文本区域中找出二进制代码的存在?

javascript - Internet Explorer 告诉我前进和后退的缓存已取消

ruby-on-rails - 使用具有单表继承的私有(private)方法

ruby-on-rails - heroku/rails Assets 预编译给出 SASS 错误

ruby-on-rails - 在 Rails 中呈现路由错误的 404 页面

css - checkbox-inline 将复选框放在文本上而不是旁边

ruby-on-rails - Ruby on Rails 源代码安全/混淆

ruby-on-rails - 使用简单形式的 gem f.association 为新操作提供 NoMethodError

ruby-on-rails - rails : Upload to Instagram programmatically?

ruby-on-rails - 防止 rspec 尝试连​​接到 mongoid