'How to use ActiveRecord in module?

require 'active_record'

module Module1
    module Module2
        class Database
            ActiveRecord::Base.establish_connection(
                :adapter  => 'postgresql',
                :host     => 'db_url',
                :username => 'db_username',
                :password => 'db_password',
                :database => 'db_name'
            )


            class People < ActiveRecord::Base
            end
        end
    end
end

I can move the ActiveRecord establish connection bit into a an initialize function, and instantiate the class however, I still get a NoMethod error when I try to call the People class.

The goal is to use it outside of the module/class by doing something like the following:

db = Module1::Module2::Database
db.People.all.each do |Person|
  puts Person
end


Solution 1:[1]

The answer is to move into another module so it doesn't require instantiation, and it's not in a class:

require 'active_record'

module Module1
    module Module2
        module Database
            ActiveRecord::Base.logger = Logger.new(STDOUT)
            class People < ActiveRecord::Base
            end
        end
    end
end

Then to use it:

# get a configuration object like this similiar to how rails is configured
dbconfig = YAML::load(File.open('config/database.yaml'))
db.establish_connection(dbconfig["database1"])
db = Module1::Module2::Database::People
db.all.each do |x|
    puts x.created_at
end

# switch between profiles
db.establish_connection(dbconfig["database2"])
db = Module1::Module2::Database::People
db.all.each do |x|
    puts x.created_at
end

config/database.yaml should resemble this:

database1:
  adapter: <adapter_name>
  username: <username>
  password: <password>
  host: <host>
  database: <database_name>

This approach is "single threaded" in the sense that you can only be connected to one database at a time because ActiveRecord connections overwrite each other as you switch between them. So switch get your data and switch again.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1