开发者

Switching connection on ActiveRecord::Schema

I'm using rails 2.3.5 and mysql.

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开发者_JS百科.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

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

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?)


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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜