Skip to content

Instantly share code, notes, and snippets.

@rsutphin
Created September 2, 2011 19:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsutphin/1189564 to your computer and use it in GitHub Desktop.
Save rsutphin/1189564 to your computer and use it in GitHub Desktop.
ActiveRecord 3.1 does not restore connection inheritance after removing a connection from a model
source :rubygems
gem 'activerecord', '~> 3.1.0'
gem 'sqlite3'
$ bundle update
[...]
$ bundle exec ruby separate_conn.rb
Creating database first.sqlite3
sqlite3 first.sqlite3 'CREATE TABLE people (id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar(255) NOT NULL)'
sqlite3 first.sqlite3 "INSERT INTO people (name) VALUES ('Jo')"
Creating database second.sqlite3
sqlite3 second.sqlite3 'CREATE TABLE people (id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar(255) NOT NULL)'
sqlite3 second.sqlite3 "INSERT INTO people (name) VALUES ('Fred')"
Connecting to first database on AR::Base
Person.all.collect(&:name): ["Jo"]
Connecting to second database on Person
Person.all.collect(&:name): ["Fred"]
Disconnecting from second database
Database connection did not revert to AR::Base's connection
#!/usr/bin/env ruby
require 'bundler'
Bundler.setup
require 'active_record'
###### Set up databases
def sh(cmd)
puts cmd
system cmd
end
{
'first.sqlite3' => 'Jo',
'second.sqlite3' => 'Fred'
}.each do |db, name|
puts "Creating database #{db}"
FileUtils.rm_rf db
sh("sqlite3 #{db} 'CREATE TABLE people (id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar(255) NOT NULL)'")
sh("sqlite3 #{db} \"INSERT INTO people (name) VALUES ('#{name}')\"")
puts
end
###### Models
class Person < ActiveRecord::Base; end
###### The problem:
puts "Connecting to first database on AR::Base"
ActiveRecord::Base.establish_connection :adapter => 'sqlite3', :database => 'first.sqlite3'
puts "Person.all.collect(&:name): #{Person.all.collect(&:name).inspect}"
puts
puts "Connecting to second database on Person"
Person.establish_connection :adapter => 'sqlite3', :database => 'second.sqlite3'
puts "Person.all.collect(&:name): #{Person.all.collect(&:name).inspect}"
puts
puts "Disconnecting from second database"
Person.remove_connection
begin
puts "Person.all.collect(&:name): #{Person.all.collect(&:name).inspect}"
rescue ActiveRecord::ConnectionNotEstablished => e
puts "Database connection did not revert to AR::Base's connection"
end
@rsutphin
Copy link
Author

rsutphin commented Sep 2, 2011

Demonstration for rails #2820. Clone, bundle update, then run separate_conn.rb to see the results.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment