dr. strange
dr. strange

Reputation: 665

How to use ActiveRecord for Multiple Environment outside Rails?

I have created a DB connection without rails for single environment and it is working fine. but want to create DB configuration for multiple environment (Ex. development, production, test etc.)

single environment db connection code (which is working fine):

require 'mysql2'
require "active_record"

# Using ActiveRecord

ActiveRecord::Base.establish_connection(
:adapter=> 'mysql2',
:database=> 'dev_db',
:username=> 'root',
:password=>'root'
)


class Planning < ActiveRecord::Base
end


p Planning.find(1)

suggestion accepted...

Upvotes: 2

Views: 961

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

What rails does may look like magic, but it's actually very simple (well, this case, at least). Here's the outline:

At startup, app loads all available database configurations. By convention, they are stored in YAML format in config/database.yml.

Then, current environment is determined. The easiest way to do this is environment variables. For example:

 MY_ENV=production ruby my_script.rb

Then, in the script, you fetch current env, pick corresponding connection configuration and use it to connect.

connection_configs = YAML.load(File.read('config/database.yml'))
current_env = ENV['MY_ENV'] || 'development' # if no value, assume development mode
ActiveRecord::Base.establish_connection(connection_configs[current_env])

Upvotes: 7

Related Questions