独立红宝石-如何从database.yml加载不同的环境 [英] Standalone ruby -- How to load different environments from database.yml
本文介绍了独立红宝石-如何从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.
- 连接到模型类的更好方法?如何将连接传递给模型?
- 我希望能够在其他环境(例如生产)上运行后台进程。
如何实现?
推荐答案
我将设置在后台流程开始时连接一次。一旦建立了连接,所有模型都将正常工作。
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]
这篇关于独立红宝石-如何从database.yml加载不同的环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文