Understanding how establish_connection works in ActiveRecord
You really do not have to call establish_connection
on each model. You can simply do next:
ActiveRecord::Base.establish_connection(
{ :adapter => 'mysql2',
:database => 'some_database',
:host => 'localhost',
:username => 'root',
:password => "" }
)
and you will have access to connection. (This chunk of code has been extracted from real code(except database name :) )).
But according to API I think that Rails does not take existing connection from other model (correct me if I am wrong).
Also here is a link to documentation. You can read more about the connection there.
I hope I helped you alittle.
When does ActiveRecord establish connections?
Answering my own question:
Whether a database connection is actually initialized during the Rails initialization process depends basically on whether ActiveRecord::Base.connection
(not establish_connection
) is called during the initialization process.
This can be related to the Rails version: for example, in Rails 3.2.13, the "active_record.validate_explain_support" initializer makes a call to connection
:
!ActiveRecord::Base.connection.supports_explain?
In Rails 3.2.14, this call is not made.
However, Rails 3.2.14 may make a call to connection
in the "active_record.set_reloader_hooks" initializer. This call may occur with the command
ActiveRecord::Base.clear_cache!
although the prepare
callback runner doesn't always seem to call this...
I also found that some gems (e.g., ActiveAdmin
) have an initialization process that will call connection
at some point.
What is the impact of ActiveRecord::Base.establish_connection in Rails?
On a normal pasenger deploy this is not a problem at all. It indeed just spawns multiple processes. They do not share any state, so there cannot be any side effects.
If you would use passenger enterprise in a multithreaded setup this could be some concern. But establish_connection, to my knowledge, takes care of grabing a new connection from the connection pool and saves it into Thread.current hash for this Class. So there should be also no side effects, like having the connection globally switched for other requests.
Take a further look at Concurrency and Database Connections with ActiveRecord
ActiveRecord::Base.establish_connection with postgresql on AWS
Here is the working code:
db_config = YAML.load_file('config/database.yml')
ActiveRecord::Base.establish_connection(db_config['production'])
How to best handle per-Model database connections with ActiveRecord?
Also, it is a good idea to subclass your model that uses different database, such as:
class AnotherBase < ActiveRecord::Base
self.abstract_class = true
establish_connection "anotherbase_#{RAILS_ENV}"
end
And in your model
class Foo < AnotherBase
end
It is useful when you need to add subsequent models that access the same, another database.
Rails cant connect to database with ActiveRecord::establish_connection
To connect again you can use
ActiveRecord::Base.connect
AR calls establish_connection only once, for ActiveRecord::Base. All subclasses use the one connection.
You can manually call establish connection yourself on some subclasses. This is very convenient for using two databases at once, e.g.
class MyMainUser < ActiveRecord::Base; end
class MyOtherDb < ActiveRecord::Base; end
class MyOtherUser < MyOtherDb; end
MyOtherDb.establish_connection ...
MyMainUser.first # uses default db
MyOtherUser.first # uses other db
You can't do queries that would cross databases though.
establish_connection when accessing model or table
All your models inherit from ActiveRecord::Base. So establish_connection is available in the model directly.
# config/database.yml
development:
# first database configuration
development_sec:
# second database configuration
Then in your model use this:
class MyModel < ActiveRecord::Base
establish_connection "#{Rails.env}_sec"
end
Or consider using a gem like connection_ninja
Related Topics
Circular Dependency Detected While Autoloading Constant User
How to Embed Regular Expressions in Other Regular Expressions in Ruby
Rails - Cannot Run App: Unable to Load the Eventmachine C Extension;
Using Memcache Client with Ruby
Block Syntax Difference Causes "Localjumperror: No Block Given (Yield)"
Capturing Groups Don't Work as Expected with Ruby Scan Method
How to List Ruby Production Only Dependencies Using Gemfile.Lock and Lockfileparser Class
Uninstall Old Versions of Ruby Gems
Equivalent of "Continue" in Ruby
Tcpserver Error: Address Already in Use - Bind(2)
How to Preserve Request Url With Nginx Proxy_Pass
Get the Value of an Instance Variable Given Its Name
How to Select Every Nth Item in an Array
Yaml How Many Spaces Per Indent