【问题标题】:ActiveRecord: how to share connections between AR-models when using ActiveRecord without RailsActiveRecord:在不使用 Rails 的情况下使用 ActiveRecord 时如何在 AR 模型之间共享连接
【发布时间】:2015-08-01 11:45:08
【问题描述】:

我试图在没有 Rails 的情况下使用 ActiveRecord 来创建一个连接到 MySql 数据库的 gem。与数据库的连接应该是可设置的,因为 gem 主要用于控制台使用,所以我不想事先在 YAML 文件中提供数据库连接信息,而是“即时”提供。这似乎带来了很多问题,因为 ActiveRecord 模型在初始化时加载了数据库信息。是否有任何其他方法可以共享数据库信息或某种方式使 active_record 不预加载数据库配置?是否有比“建立连接”更好的方法来共享连接信息?

这是我的代码:

class Blog 
  @@options = { :adapter  => "mysql2" }

  def self.options
    @@options
  end

  def initialize(options = Hash.new)
    @@options = {
      :adapter  => "mysql2",
      :host     => options[:host] || "localhost",
      :username => options[:user] || "root",
      :password => options[:pass] || "",
      :database => options[:db] || "my_blog"
    }
  end
end

module Foobar
  class Post < ActiveRecord::Base
    establish_connection(Blog.options)
  end
end

在命令行上

Blog.new(user:"foo",pass:"bar",db:"bang")
p=Foobar::Post.all

【问题讨论】:

  • 因为是我写的,我正在开发各种命令行脚本,它们应该在没有 Rails 的情况下运行。这不是用于 Web 开发,而是用于控制台(终端)脚本。
  • 如果脚本很容易使用 mysql CLI 否则使用 Rails rake 任务以节省大量时间

标签: ruby-on-rails ruby activerecord


【解决方案1】:

你应该打电话给ActiveRecord::Base.establish_connection(...)

class Blog
  # No need to use initializer method if you don't intend
  # to use initialized instance. Static method will do better.
  def self.connect(options = Hash.new)
    ActiveRecord::Base.establish_connection(
      adapter:  "mysql2",
      host:     options[:host] || "localhost",
      username: options[:user] || "root",
      password: options[:pass] || "",
      database: options[:db] || "my_blog"
    )
  end
end

module Foobar
  class Post < ActiveRecord::Base
    # Connection is done via Blog model
  end
end

Blog.connect(username: 'john', password: 'qwerty')
posts = Foobar::Post.all

【讨论】:

  • 哇,感谢您快速而雄辩的回答!这正是我想要的!
猜你喜欢
  • 1970-01-01
  • 2012-12-23
  • 1970-01-01
  • 2011-05-17
  • 1970-01-01
  • 1970-01-01
  • 2017-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多