Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 948
Tommy Avatar asked Jan 20 '11 02:01

Tommy


People also ask

Can Rails connect to multiple databases?

Rails now has support for multiple databases so you don't have to store your data all in one place. At this time the following features are supported: Multiple writer databases and a replica for each. Automatic connection switching for the model you're working with.

What is ActiveRecord :: Base in Rails?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module... ActiveRecord is defined as a module in Rails, github.com/rails/rails/tree/master/activerecord/lib/…

What is schema RB Rails?

The schema. rb serves mainly two purposes: It documents the final current state of the database schema. Often, especially when you have more than a couple of migrations, it's hard to deduce the schema just from the migrations alone. With a present schema.


1 Answers

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.

like image 170
Chris Avatar answered Sep 19 '22 12:09

Chris