【问题标题】:How to execute a query per db connection如何为每个数据库连接执行查询
【发布时间】:2020-08-10 19:23:55
【问题描述】:

我目前正在执行以下操作,但效率低下,因为它在每次操作之前都会调用它

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 转换成这样的东西吗?也许作为初始化程序?我不知道从哪里开始

【问题讨论】:

  • 这是可以在服务器端设置的吗?我不确定 Rails 是否可以开箱即用。
  • 我把一些东西当作一个似乎可以工作的初始化程序,但我不确定重写 configure_connection require 'active_record/connection_adapters/postgresql_adapter' class ActiveRecord::ConnectionAdapters::PostgreSQLAdapter def configure_connection execute('SET intervalstyle = iso_8601', 'SCHEMA') end end 是否是个好主意
  • 可能不是一个好主意,这就是为什么我要询问这样的默认设置的服务器端设置。

标签: ruby-on-rails activerecord rails-activerecord


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 2022-11-14
    • 1970-01-01
    • 2021-03-18
    • 2012-04-08
    • 2019-09-06
    相关资源
    最近更新 更多