当前位置:  开发笔记 > 编程语言 > 正文

Rails - 两个应用程序之间的共享数据库表

如何解决《Rails-两个应用程序之间的共享数据库表》经验,为你挑选了1个好方法。

我们将很快发布一个配套的Rails应用程序到我们现有的Rails应用程序.我们将在同一台服务器上与现有应用程序一起运行配套应用程序.

我的问题涉及数据库.我的托管服务提供商通常会为新应用程序配置第二个不同的数据库 - secondappname_production.但是,应用程序之间有一系列共享表.这些共享表也由一系列cron作业维护.如果可能的话,我希望避免重复这些表(以及cron作业).

有没有办法可以将这些共享表放在Rails应用程序可以利用的共享数据库中?有关如何配置或文档指针的任何建议?

非常感谢!

编辑:澄清为什么我不想从同一个数据库运行这两个应用程序:两个应用程序都有相同名称的模型(但模型的不同属性等),所以我宁愿不运行两个相同的DB ....



1> Andrew Kukle..:

You can have some models in one database (the ones that you want to share), and others in the new app's own database (so they don't collide with the existing app).

To specify a different database for a particular model, try something like this:

class SharedModelBase < ActiveRecord::Base
  self.abstract_class = true
  establish_connection(ActiveRecord::Base.configurations["shared_db_connection_#{RAILS_ENV}"])
end

Now, use this as a base class for your shared models, and you should be good to go.

Part of your question is best practices, so a couple of other options.

One option is to not even try to access to the db directly, but instead build an integration between the apps using ActiveResource. Have the original app provide a RESTful interface to these tables, and consume it in the new app, and don't share the db at all. I like this option, but may not be clever for your situation.

Another option is to refactor these shared tables into their own database, and have both the rails apps access that db. You could even end up writing services (e.g. restful interface) to this shared data to be used by both apps, and then you are nicely decoupled.

Consider the complexities of when this shared db structure changes. If you are sharing the tables directly, both rails apps could have to be changed simultaneously to accommodate the change - you have linked your release schedule now, these apps are now coupled. If you wrap the access to the db in services, this can provide abstraction as you can serve both the old structure and new structure simultaneously by deploying the new updated service at the same time as the old service interface. It all depends on your app if such complexity is worth it.

推荐阅读
黄晓敏3023
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有