连接到数据库后在 Rails 中运行原始 SQL [英] Run Raw SQL in Rails after connecting to Database

查看:26
本文介绍了连接到数据库后在 Rails 中运行原始 SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的 Rails 应用程序在与数据库建立连接后运行原始 sql 命令.它属于哪个文件?配置/初始值设定项之一?

I'd like my Rails app to run a raw sql command after it establishes the connection to the DB. In which file does that belong? One of the config/initializers?

推荐答案

我使用monkeypatching 强制MySQL 使用严格模式,同样的方法也适用于您的情况.此代码属于初始化程序.

I use monkeypatching to force strict mode for MySQL, the same approach should also work in your case. This code belongs in an initializer.

class ActiveRecord::ConnectionAdapters::Mysql2Adapter

private
  alias_method :configure_connection_without_autocommit, :configure_connection

  def configure_connection
    configure_connection_without_autocommit
    execute "COMMAND_TO_ENABLE_AUTOCOMMIT"
  end
end

作为参考,这里是 源Mysql2Adapter 的代码.

这篇关于连接到数据库后在 Rails 中运行原始 SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆