RSK
RSK

Reputation: 17516

Ruby ActiveRecord Dynamic Model creation

I am trying to establish a multiple DB connection with ActiveRecord.Currently I need to insert data into total 2 Databases. There is a possibility for increase in the No.Of databases.

So I created 2 classes dynamically which will Extend from ActiveRecord::Base

Object.const_set("Connection1",Class.new(ActiveRecord::Base) do
  self.abstract_class = true
  self.establish_connection({
    :host=>"localhost", :username=>"root", :password=>"root", :database=>"db1", :encoding=>"utf8", :adapter=>"mysql2"})
end)

Object.const_set("Connection2",Class.new(ActiveRecord::Base) do
  self.abstract_class = true
  self.establish_connection({
    :host=>"localhost", :username=>"root", :password=>"root", :database=>"db2", :encoding=>"utf8", :adapter=>"mysql2"})
end)

Then I created Dynamic models extends from each class accordingly

Object.const_set("ConnectionUser1",Class.new(Connection1) do
  self.table_name = 'user'
  def self.foo
    all.count
  end
end)

Object.const_set("ConnectionUser2",Class.new(Connection2) do
  self.table_name = 'user'
  def self.foo
    all.count
  end
end)

Then when I tried to call foo method

p ConnectionUser1.foo
p ConnectionUser2.foo

It gives me ActiveRecord::ConnectionNotEstablished Error.

I heard that if the model doesn't have connection ActiveRecord will take connection of their parent.

So according to this ConnectionUser1 should use the connection of Connection1 and ConnectionUser2 use the connection of Connection2.

Then why ActiveRecord fails to Establish Connection?

Any help will be appreciated.
Thank you.

Upvotes: 2

Views: 884

Answers (1)

Soundar Rathinasamy
Soundar Rathinasamy

Reputation: 6728

Take a look at below link which shows that how to use multiple database with ActiveRecord.

How do i work with two different databases in rails with active records?

Upvotes: 1

Related Questions