如何对每个数据库连接执行查询(How to execute a query per db connection)

18 IT屋

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

解决方案

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

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


  class ApplicationController< ActionController :: Base 
before_action:set_intervalstyle

private
def set_intervalstyle
ActiveRecord :: Base.connection.exec_query(" SET intervalstyle = iso_8601"," SCHEMA" ;)
结束
结束

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


  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



 需要'active_record / connection_adapters / postgresql_adapter'

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

def configure_connection
configure_connection_without_interval
execute('SET intervalstyle = iso_8601','SCHEMA')
结束
结束

本文地址:IT屋 » 如何对每个数据库连接执行查询