Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A callback for ActiveRecord database connections?

Is there any way to hook into ActiveRecord connection creation? I want to run some code whenever a connection has just been created.

I feel like it might be a way to set a MySQL variable on the connection, since "variables" in database.yml doesn't seem to work for me. (How to turn off MySQL strict mode in Rails)

like image 739
mahemoff Avatar asked Jan 30 '14 01:01

mahemoff


2 Answers

The ConnectionAdapter defines two callbacks :checkout (connect) and :checkin (disconnect). You can use it for specific adapter as

ActiveRecord::ConnectionAdapters::MysqlAdapter.set_callback :checkout, :after do
  raw_connection.set_your_variables ...
end

Or you can use ActiveRecord::Base.connection.class for whatever adapter is currently declared in database.yml

like image 161
Vladimir Avatar answered Nov 11 '22 20:11

Vladimir


Also, if you need to configure your model after connection has been made and column information was retrieved, you can redefine load_schema! class method in model.

See: https://github.com/rails/rails/pull/31681#issuecomment-357113030

like image 2
Envek Avatar answered Nov 11 '22 20:11

Envek