rails/rails — Issue #5259: ConnectionNotEstablished with connection on subclass of AR::Base
Author: mlartz
Created: 2012-03-03 16:14:22+00:00
State: open

I'm using ActiveRecord outside of Rails and calling establish_connection on a abstract_class sublcass of ActiveRecord::Base (to protect my connection in case anyone else is using AR). It was working just fine with AR 3.0.9, but I recently attempted to upgrade to AR 3.2.2. Now, when I hit a "nested" query from a has_many, I get a ActiveRecord::ConnectionNotEstablished. If I call establish_connection on ActiveRecord::Base, instead of the DB abstract subclass, everything works fine. I've stripped out a minimal example below, which should be self- contained, as well as a snippet that highlights the problem. Is this a bug?

This is the offending code:

``` ruby
Employer.all.each do |employer|
p employer.employees
end
```

Self-contained script:

``` ruby
#!/bin/env ruby
require 'sqlite3'
require 'active_record'
require 'logger'
ActiveRecord::Base.logger = Logger.new STDOUT
class DB < ActiveRecord::Base
self.abstract_class = true
end
class Employer < DB
has_many :employees
end
class Employee < DB
end
# If establish_connection is instead called on AR::Base, this works fine.
DB.establish_connection(:adapter => "sqlite3",
:database => "./db.sqlite")
DB.connection.create_table(:employers) do |t|
t.primary_key :id
end
DB.connection.create_table(:employees) do |t|
t.primary_key :id
t.integer :employer_id
end
Employer.create!.employees << Employee.create!
Employer.all.each do |employer|
p employer.employees
end
```