如何使用Rails手动连接MYSQL数据库?

时间:2017-06-05 15:59:45

标签: mysql ruby-on-rails ruby

我想连接到MySQL数据库而不将其添加到database.yml。如何在该数据库上连接和运行查询?

我知道我需要做这样的事情,但是实际连接到特定IP /端口的代码是什么?

query = "SELECT 1"
ActiveRecord::Base.connection.execute(query)

1 个答案:

答案 0 :(得分:2)

您可能想尝试ActiveRecord::Base.establish_connection

文档示例:

ActiveRecord::Base.establish_connection(
  :adapter  => "mysql",
  :host     => "localhost",
  :username => "myuser",
  :password => "mypass",
  :database => "somedatabase"
)

自:

https://apidock.com/rails/ActiveRecord/Base/establish_connection/class