Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a query per db connection

I'm currently doing the following which works but is inefficient since it's calling it before every action

class ApplicationController < ActionController::Base
  before_action :set_intervalstyle
  
  private
  def set_intervalstyle
    ActiveRecord::Base.connection.exec_query("SET intervalstyle = iso_8601", "SCHEMA")
  end
end

I noticed here that they're registering this command per connection

  alias_method :configure_connection_without_interval, :configure_connection
  define_method :configure_connection do
    configure_connection_without_interval
    execute('SET intervalstyle = iso_8601', 'SCHEMA')
  end

Could someone help me figure out how to convert my before_action into something like this? Maybe as an initializer? I'm not sure where to start

like image 789
vince Avatar asked Oct 30 '25 14:10

vince


1 Answers

Not sure if this is a good idea but so far this works and hasn't had any side effects

config/initializers/set_intervalstyle.rb

require 'active_record/connection_adapters/postgresql_adapter'

class ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
  alias_method :configure_connection_without_interval, :configure_connection

  def configure_connection
    configure_connection_without_interval
    execute('SET intervalstyle = iso_8601', 'SCHEMA')
  end
end
like image 168
vince Avatar answered Nov 01 '25 07:11

vince



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!