Standalone ruby​​ -- 如何从 database.yml 加载不同的环境 [英] Standalone ruby -- How to load different environments from database.yml

查看:10
本文介绍了Standalone ruby​​ -- 如何从 database.yml 加载不同的环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have a background process that modifies records in a database. The models connect to the database using something like this:

dbconfig = YAML::load(File.open('database.yml'))
ActiveRecord::Base.establish_connection(dbconfig["development"])
class Clcar < ActiveRecord::Base
 ....
end

All model classes have those lines at the top.

I agree that's a bad way of doing it.

  1. Is there a better way to get a connection to a model class? How do I pass the connection to the model?
  2. I want to be able to run my background process with a different environment, say "production".

How do I achieve that?

解决方案

I would set up the connection once at the start of your background process. Once you've established the connection once, all of the models will work correctly anyway.

Your connection establishment code would look something like this:

@environment = ENV['RACK_ENV'] || 'development'
@dbconfig = YAML.load(File.read('config/database.yml'))
ActiveRecord::Base.establish_connection @dbconfig[@environment]

这篇关于Standalone ruby​​ -- 如何从 database.yml 加载不同的环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆