Ruby on rails Rails控制台中数据库之间的复制
我有三个数据库: A.mynewapp_psql Postgres B.旧产品psql Postgres C.老博客帖子 每个都在database.yml中定义 我正在使用mynewapp_psql作为新应用程序的数据库。在这个应用程序中,我希望能够从我的两个旧数据库复制选定的材料 我的尝试已根据响应更新Ruby on rails Rails控制台中数据库之间的复制,ruby-on-rails,database,rails-console,Ruby On Rails,Database,Rails Console,我有三个数据库: A.mynewapp_psql Postgres B.旧产品psql Postgres C.老博客帖子 每个都在database.yml中定义 我正在使用mynewapp_psql作为新应用程序的数据库。在这个应用程序中,我希望能够从我的两个旧数据库复制选定的材料 我的尝试已根据响应更新 old_db = ActiveRecord::Base.establish_connection(:database => 'old_blogposts_mysql'... etc) p
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
它应该从我的旧数据库中获取每个产品,并在新数据库中创建一个新的等效产品
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
我真的更喜欢通过控制台进行操作,我不能直接复制数据库,因为我需要过滤和更改数据。控制台不是动态访问数据库的唯一方法。考虑为每个数据库使用ActiveRecord连接的定制ruby任务
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
所以你的案子是一个失去联系的案子。如何建立一个到当前数据库的新连接,使您的代码变成这样
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
谢谢,这让我更接近了。但是,这不只是连接到另一个数据库,而保留到原始数据库的连接吗?我的意思是,最后一行my_post=post.new将不仅仅在canvas_测试数据库中创建新的post,而不是在我正在创建的原始mynewapp_psql数据库中创建新的post?result=ActiveRecord::Base.connection.executeSELECT*FROM posts;-我想这是我唯一需要的。然后我可以使用result,例如result.first来获取数据。再次感谢!很抱歉有这么多评论。我意识到这并不能真正解决问题,因为如果我建立到我的mysql数据库的连接,我就不能再访问控制台中的原始数据库,我真的想使用控制台。你的声明是错误的,你可以打开多个连接。啊,@Areba必须让你明白这一点。哦,很高兴能帮忙。