Run Raw SQL in Rails after connecting to Database

巧了我就是萌 提交于 2019-12-12 01:55:36

问题


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?


回答1:


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

For reference, here's the source code for Mysql2Adapter.




回答2:


I think You can write a rake filter, through which you can fire a query before each inbound call. You can read more about this here.



来源:https://stackoverflow.com/questions/29224331/run-raw-sql-in-rails-after-connecting-to-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!