0

I want to have a method on a class to copy the object and all of the relationships to another database that has the same structure. How can I accomplish this?

Chris McKnight
  • 8,540
  • 4
  • 29
  • 31
  • Hmm, backup then restore in the new DB? – MrYoshiji May 09 '14 at 18:10
  • We need more detail. Is this a one-time task? Then MrYoshiji’s suggestion works. Will this be done regularly? Are you worried about keeping the objects in sync; if you duplicate the object and its dependents once and a second time, will you need to overwrite the original copy? – Buck Doyle May 09 '14 at 18:14
  • I'm not worried about synchronizing the objects. I just want to push them into another database when an action occurs. Firing the action a second time would overwrite the objects in the second database. This would happen on a per object basis. – Chris McKnight May 09 '14 at 20:31

1 Answers1

-1

You could have a look at dbcharmer, which will allow to switch connections on the fly, so copying a record would be a piece of cake I guess.

[UPDATE] Small example: you do not have to mess with the ActiveRecord::Base.connection

Suppose your database.yml looks like this:

production:
  blah:
    adapter: mysql
    username: blah
    host: blah.local
    database: blah

  foo:
    adapter: mysql
    username: foo
    host: foo.local
    database: foo 

Then you should be able to do something like (disclaimer: I only read the documentation myself)

original_user = User.on_foo.find(99)

User.on_blah.create(name: original_user.name, ...)

I guess you could even do something like

User.on_blah do 
  original_user.save
end
nathanvda
  • 49,707
  • 13
  • 117
  • 139
  • I looked at dbcharmer but I don't want it to mess up ActiveRecord::Base's connection or the connection of other objects of the same class. – Chris McKnight May 09 '14 at 20:35
  • As I read the documentation there is no need to mess with the `ActiveRecord::Base.connection`, but you can just perform statements for a specific connection, using the `.on_` command. I added a small example. – nathanvda May 09 '14 at 22:36
  • I'm not sure this is the way to go. I need to duplicate data from all of the relationships on the object as well. I am running into problems with mass assignment, validations, and relationships. – Chris McKnight May 12 '14 at 17:01
  • In that case Shouldn't you consider something a little more low level, on database level? Like a script, or import/export? It is a bit unclear what you are trying to achieve for me. Maybe use an api? Sync databases, with master/slave? – nathanvda May 12 '14 at 17:06
  • True. I was thinking about having some SQL do it or using an API. – Chris McKnight May 12 '14 at 17:15
  • I could just use the mysql adapter directly and generate a bulk insert statement. – Chris McKnight Jun 13 '14 at 18:52