ActiveRecord: how to exchange connections between AR models when using ActiveRecord without Rails

I am trying to use ActiveRecord without Rails to create a gem that connects to a MySql database. The database connection needs to be established as gem is mainly for console use, so I don't want to provide the database connection information in the YAML file ahead of time, but provide it on the fly. This seems to be causing a lot of problems, as ActiveRecord models load database information on initialization. Is there any other way to exchange information about the database or somehow make active_record not preload the database configurations? Maybe a better way to share connection information than "set_connection"?

here is my code:

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

      

on the command line

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

      

+3


source to share


1 answer


You should just call 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

      

+1


source







All Articles