如何对每个数据库连接执行查询

问题描述

我目前正在执行以下操作,但效率不高,因为它是在每次操作之前调用

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

我注意到here,他们正在为每个连接注册此命令

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

有人可以帮我弄清楚如何将我的before_action转换成这样吗?也许作为初始化器?我不确定从哪里开始

解决方法

不确定这是否是个好主意,但到目前为止,它仍然有效并且没有任何副作用

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