我目前正在做以下工作但效率低下,因为它在每个 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
我注意到了 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
关于ruby-on-rails - 如何为每个数据库连接执行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63346731/