Switching Connection to ActiveRecord :: Schema

I am using rails 2.3.5 and mysql.

I have a TableA model and another TableB model. TableA is completely fine ... but I need to swap connections for TableB. I am connecting to another server elsewhere, so I have to check if this table exists. If it is not, I will 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 

I noticed that TableB.establish_connection (new_database_params) connects me to the new server. This is completely normal.

When I try to create a new table, I still have to call ActiveRecord :: Base to replace the connection. Is there a way to exchange a connection for ActiveRecord :: Schema? (similar to Model.establish_connection?)

+6
ruby-on-rails
source share
1 answer

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

Under the hood, Schema is a subclass of Migration, and it calls instance_eval in the block that you provide. Therefore, we are in the scope of the Migration class and can change the @connection instance variable to connect 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 understand that this answer is probably too late! But it may be useful to someone.

+8
source share

All Articles