title: Rake task copy between databases
body: <p>I have a Rails 4 app with a Mongoid database and want to introduce a sandbox environment for testing purpose. There is some data (two models), that I want to copy from the production db to the sandbox.</p>
  
  <p>I would do this with a rake task, that is called by a cronjob. However, inside this rake task, I'm not sure how to establish two connections to the databases, and use the same model for different databases.</p>
  
  <p>I was also thinking of doing it at the mongodb layer (like they do here <a href="https://stackoverflow.com/questions/11554762/how-can-i-copy-collection-to-another-database-in-mongodb">How to copy a collection from one database to another in MongoDB</a>), but one model consists of data, that only should be partially copied to the sandbox database. Therefore, I think I have to do it inside the Rails environment.</p>
  
  <p>In this rake task, I can all my articles, but I don't know how to "push" them into the sandbox database:</p>
  
  <pre><code>namespace :sandbox do
    desc "Syncs production -&gt; sandbox data"
      task(:sync =&gt; :environment) do |t, args|
        Article.all.each do |article|
          if my_model1.state == :active
            # here it should sync article to the sandbox models
  
            # and then, it should also sync all the comments to the sandbox models
            article.comments
          end
        end
      end
    end
  end
  </code></pre>