In some of my Rails applications, my ActiveRecord models seem to establish db connections on initialization (e.g., when I do rails console
), while in others connections seem to be established only when I reference the model class or instantiate a model object.
For example, I just went to one application, opened Rails console and wrote:
SomeModel.connected?
and it returned false
. I went to another application, entered the same command (for a different model), and it returned true
. I went to a third application and entered the same command. This time, it waited a moment and then returned true
, which made me think that the connected?
method triggered the connection for some reason.
This difference in behavior doesn't seem related to Rails versions or the contents of the models. It could be something weird I've done in my initializers, but I don't think so.
So when does Rails establish connections? Or what is the expected behavior?
ADDITIONAL INFO
I'll add that it doesn't seem like connected?
returns false because Rails cannot connect to the database.
For example, in my first application I do:
SomeModel.connected?
# => false
SomeModel.table_exists? # or any other command that makes Rails look at db
# => true
SomeModel.connected?
# => true
Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.
The active record pattern is an approach to accessing data in a database. A database table or view is wrapped into a class. Thus, an object instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save.
ActiveRecord is commonly used with the Ruby-on-Rails framework but you can use it with Sinatra or without any web framework if desired.
ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With