在 ActiveRecord::Schema 上切换连接 [英] Switching connection on ActiveRecord::Schema

查看:27
本文介绍了在 ActiveRecord::Schema 上切换连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 rails 2.3.5 和 mysql.

I'm using rails 2.3.5 and mysql.

我有一个模型 TableA 和另一个模型 TableB.TableA 完全没问题……但我需要为 TableB 交换连接.我正在连接到别处的另一台服务器,所以我必须检查该表是否存在.如果没有,我将创建一个新表.

I've got a model TableA and another model TableB. TableA is totally fine.. but I need to swap connections for TableB. I'm connecting to another server elsewhere so I have to check if that table exists. If it doesn't, I'll create a new table.

TableB.establish_connection(new_database_params)
unless TableB.table_exists?
  ActiveRecord::Base.establish_connection(new_database_params)
  ActiveRecord::Schema.define do
    create_table :table_bs do |t|
      t.column :text, :string
    end
  end
  ActiveRecord::Base.establish_connection("#{RAILS_ENV}")      
end

我注意到 TableB.establish_connection(new_database_params) 将我连接到新服务器.那完全没问题.

I noticed that TableB.establish_connection(new_database_params) connects me to new server. That's totally fine.

当我尝试创建一个新表时,我仍然需要调用 ActiveRecord::Base 来交换连接.有没有办法交换 ActiveRecord::Schema 上的连接?(类似于Model.establish_connection?)

When I'm trying to create a new table, I still have to call ActiveRecord::Base to swap the connection. Is there a way to swap the connection on ActiveRecord::Schema? (similar to Model.establish_connection?)

推荐答案

从概念上讲,我遇到了完全相同的问题.我想继承 ActiveRecord::Base 并为该连接构建一个架构.我花了很长时间才弄明白,并深入研究了 ActiveRecord::Base、Schema 和 Migration,但我找到了一个有效的解决方案,而且非常简单.

Conceptually I had exactly the same problem. I wanted to subclass ActiveRecord::Base and build a schema for that connection. It took me a long time to figure out, and lots of diving into ActiveRecord::Base, Schema and Migration, but I found a solution that works, and it's really very simple.

在幕后,Schema 是 Migration 的子类,它在您提供的块上调用 instance_eval.因此,我们在 Migration 类的范围内,可以将其 @connection 实例变量更改为 ActiveRecord::Base 子类的连接,即

Under the hood, Schema is a subclass of Migration, and it calls instance_eval on the block you provide. Therefore, we are in the scope of the Migration class and can alter its @connection instance variable to the connection of the ActiveRecord::Base subclass, i.e.

ActiveRecord::Schema.define do
  @connection = TableB.connection
  create_table :table_bs do |t|
    t.column :text, :string
  end
end

我意识到这个答案可能晚了一年!但它可能仍然对某人有用.

I realise this answer is probably a year too late! But it may still be of use to someone.

这篇关于在 ActiveRecord::Schema 上切换连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆