【问题标题】:Rails Use models, namespaced and connected to different dbRails 使用模型,命名空间并连接到不同的数据库
【发布时间】:2019-05-01 02:51:47
【问题描述】:

我有一个 rails 5 应用,需要报告功能。我现在想将它保留在应用程序中,而不是使用 rails 引擎。报告功能连接到 Heroku 关注者数据库。

我可以复制我的普通模型并将它们用作连接到关注者数据库的父类的子类,如下所示?

module Reporting
 class Base < ActiveRecord::Base
   self.abstract_class = true
   establish_connection("follower_database")
 end
end

module Reporting
  class User < Reporting::Base
    # I would like to avoid copying and pasting all the user model code here and have some fancy way for it to just inherit or included it all so when we add new associations etc. the reporting classes automatically get it..
  end
end

【问题讨论】:

  • establish_connection 是 ActiveRecord::Base 的方法。不管你是否使用 Rails,都应该使用 ActiveRecord::Base。

标签: ruby-on-rails ruby heroku ruby-on-rails-5 rails-activerecord


【解决方案1】:

您需要将完整的连接配置传递给establish_connection 方法。要共享普通 User 类的功能,您可以从该类继承并包含来自模块的数据库连接,例如

module FollowerDatabaseConnection
  def self.included(base)
    base.establish_connection base.configurations['follower_database']
  end 
end

class Reporting::User < User
  include FollowerDatabaseConnection
end

并在database.yml中定义连接配置

# database.yml
common:
  ...
development:
  ...
...
follower_database:
  adapter: ..
  ...

【讨论】:

  • 谢谢,我想弄清楚的是在我的示例中,命名空间的用户类如何从 norma 用户类继承所有功能...无需复制和粘贴
  • 编辑了地址评论的答案。
猜你喜欢
  • 1970-01-01
  • 2012-09-10
  • 1970-01-01
  • 2015-10-08
  • 2017-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-13
相关资源
最近更新 更多