Carlos Roque
Carlos Roque

Reputation: 458

ActiveRecord::Base doesn't belong in a hierarchy descending from ActiveRecord when connecting to two sqlserver databases

I use ActiveRecord on a non rails app.I am connecting to two SQLserver databases using this method

class MyBase > ActiveRecord::Base
  this.abstract_class = true
end
class Order > MyBase
end
class MyBase2 > ActiveRecord::Base
  this.abstract_class = true
end
class Order2 > MyBase2
end

then connecting to the dbs by calling

MyBase.establish_connection(config1)
MyBase2.establish_connection(config2)

this was working great in AR3 but I am migrating to AR4 and when do something like this

puts Order.last.inspect
puts Order2.last.inspect 

I am getting this error on the second puts, the first call works as expected.

ActiveRecord::ActiveRecordError: ActiveRecord::Base doesn't belong in a hierarchy descending from ActiveRecord

If i swap the calls then the one that used to fails works and the one that worked fails. so it seems to be an issue with switching connections it only seems to affect connections that use the activerecord-sqlserver-adapter if i use mysql or pg databases this problem doesn't happen Any help would be appreciated

Upvotes: 0

Views: 103

Answers (1)

Carlos Roque
Carlos Roque

Reputation: 458

So this was a weird problem. I had to migrate connection logic into the base classes. For some reason the second call to establish_connection was making AR4 "forget" the first establish_connection. this is weird since this was working on AR3. my models now look like this

First Base Class

class MyBase > ActiveRecord::Base
  this.abstract_class = true
  begin
    # try the rails ways first
    establish_connection(:database1_name)
  rescue
    # this is probably a ruby app (non-rails)
    config_file = nil

    # do we have a database file?
    if File.exist?('config/database.yml')
      config_file = 'config/database.yml'
    end
    # return if we could not find a config_file
    return if config_file.nil?

    dbconfig = YAML::load(File.open(config_file))
    establish_connection(dbconfig[:database1_name])
  end
end

class Order > MyBase
end

Second Base Class

class MyBase2 > ActiveRecord::Base
  this.abstract_class = true
  begin
    # try the rails ways first
    establish_connection(:database2_name)
  rescue
    # this is probably a ruby app (non-rails)
    config_file = nil

    # do we have a database file?
    if File.exist?('config/database.yml')
      config_file = 'config/database.yml'
    end
    # return if we could not find a config_file
    return if config_file.nil?

    dbconfig = YAML::load(File.open(config_file))
    establish_connection(dbconfig[:database2_name])
  end
end
class Order2 > MyBase2
end

Upvotes: 0

Related Questions