在Rails中的Rake任务中重现生产环境

时间:2016-07-11 17:14:59

标签: database ruby-on-rails-4 mongoid production-environment

我正在尝试将我的所有生产数据库(我在Mongo中)复制到我的暂存环境中。所以我正在尝试建立一个任务。首先,我需要连接到生产环境才能访问生产中的所有模型(Model.all.each ...)但我不知道如何重现生产环境。我知道在控制台中我可以“导出RAILS_ENV = heroku_production”,但我不知道如何在Rake任务中执行此操作。这就是我现在正在尝试但它不起作用,因为我打印Rails.env并打印“开发”...所以我有点迷失

namespace :db do
  namespace :sync_production_staging do
    desc "Copy production database to staging"
    task :staging => :environment do

      system "export RAILS_ENV=heroku_production"

      ap Rails.env

      ap User.all
    end
  end
end

1 个答案:

答案 0 :(得分:0)

I have a script that copies my database from heroku to my local its a really strait forward process, I am sorry that this is PG and not mongo but I am sure that this should help

#lib/tasks/db.rake
namespace :db do
  desc "Import most recent database dump"
  task :import_from_prod => :environment do
    puts 'heroku run pg:backups capture --app sushi-prod'
    restore_backup 'sushi-prod'
  end

  def path_to_heroku
    ['/usr/local/heroku/bin/heroku', '/usr/local/bin/heroku'].detect {|path| File.exists?(path)}
  end

  def heroku(command, site)
    `GEM_HOME='' BUNDLE_GEMFILE='' GEM_PATH='' RUBYOPT='' #{path_to_heroku} #{command} -a #{site}`
  end

  def restore_backup(site = 'sushi-prod')
    dump_file = "#{Rails.root}/tmp/postgres.dump"
    unless File.exists?(dump_file)
      pgbackups_url = heroku('pg:backups public-url -q', site).chomp
      puts "curl -o #{dump_file} #{pgbackups_url}"
      system "curl -o #{dump_file} '#{pgbackups_url}'"
    end
    database_config = YAML.load(File.open("#{Rails.root}/config/database.yml")).with_indifferent_access
    dev_db = database_config[Rails.env]
    system "pg_restore -d #{dev_db[:database]} -c #{dump_file}".gsub(/\s+/,' ')
    puts
    puts "'rm #{dump_file}' to redownload postgres dump."
    puts "Done!"
  end
end