Question

I have three databases:

  • A. mynewapp_psql (Postgres)
  • B. old_products_psql (Postgres)
  • C. old_blogposts_mysql (Mysql)

Each is defined in database.yml

I'm using A (mynewapp_psql) as the database for my new app. In this app I want to be able to copy selected material from my two older databases.

My attempt (updated according to response)

old_db = ActiveRecord::Base.establish_connection(:database => 'old_blogposts_mysql'... etc)
posts = old_db.connection.execute("select * from posts'")
posts.each do |p|
  NewPost.create(:name => p.name.downcase) #NewPost should add Post in A. (mynewapp_psql)
end

It should take each product from my old database and create a new equivalent in the new database.

I really prefer doing it through the console and I can't copy the database straight over since I need to filter and alter the data.

Was it helpful?

Solution

So your case is one of Lost connection. How about Establishing a new connection to your current DB so that your code becomes like this

old_db = ActiveRecord::Base.establish_connection(:database => 'old_blogposts_mysql'... etc)
posts = old_db.connection.execute("select * from posts'")
new_db = ActiveRecord::Base.establish_connection(:database => 'mynewapp_psql'... etc)
posts.each do |p|
  NewPost.create(:name => p.name.downcase) #NewPost should add Post in A. (mynewapp_psql)
end

OTHER TIPS

The console is not the only way to dynamically access your databases. Think about a custom ruby task for your purposes using ActiveRecord connections for each database.

require 'pg'
require 'active_record'

ActiveRecord::Base.establish_connection(
  adapter:  'postgresql', # or 'mysql2' or 'sqlite3'
  host:     'localhost',
  database: 'canvas_test',
  username: 'joe',
  password: 'shiitake'
)

# EXEC raw SQL
ActiveRecord::Base.connection.execute("SELECT * FROM posts;")

class Post < ActiveRecord::Base
end

# READ all posts
puts Post.count
=> #<Post:0xb96582cc>
=> ...

# CREATE one new post
my_post = Post.new
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top