【问题标题】:Using two or more databases in rails project在 Rails 项目中使用两个或多个数据库
【发布时间】:2010-06-15 04:13:39
【问题描述】:

我正在为不同的项目使用外部用户数据库。

现在我的项目中有 School 模型,它 has_many users 并且 users 有很多学校。

class User < ActiveRecord::Base
  establish_connection "#{RAILS_ENV}_tunnel"
  has_many :memberships
  has_many :schools, :through => :memberships
end

class School < ActiveRecord::Base
  has_many :memberships
  has_many :users, :through => :memberships
end

class Membership < ActiveRecord::Base
  belongs_to :user
  belongs_to :school
end

那么我现在有什么问题:

  • 我无法调用 school.users(因为成员资格表在我的 PROJECT 数据库中,而不是在外部 USERS 数据库中),但我可以调用 user.schools
  • 我无法以这种方式更新:current_user.school.find(params[:id]).update_attributes(params[:school]),因为它以这种方式打开只读连接。

我了解如何解决这个问题,即

school.users 我可以这样称呼:

class School < ActiveRecord::Base
  has_many :memberships
  # has_many :users, :through => :memberships

  def users
    User.where("users.id in (?)", self.connections.map(&:user_id))
  end
end

但这些技巧还不够。因为现在我无法添加像 school.users &lt;&lt; User.find(203)school.users.find(params[:user_id]) 之类的用户以及其他功能,has_many 关系给了我。

所以问题是如何操作两个数据库,这两个数据库通过多对多关系相互连接,并提供完整的功能支持。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    我认为在 Rails 中没有一种方法可以在具有完整功能支持的情况下执行此操作 - 我认为您最好尝试使用类似 MySQL's federated tables 的东西来带来远程数据库表进入您的生产数据库。

    【讨论】:

    • +1 这听起来像一个更简单的解决方案,头痛的可能性较小。
    • 非常有趣。但是同步源和我的表副本的速度有多快?
    • @fl00r - 它不是表的副本 - 它是与其他数据库的直接连接,因此同步不是问题。
    【解决方案2】:

    在 oracle 中,我将为此使用数据库链接。

    我不完全确定,但我发现在mysql中你可以写

    select * from db1.users , db2.schools where db1.users.school_id = db2.schools.id
    

    那么你就可以通过在模型中显式声明表名来在 Rails 中使用它:

    class School
      set_table_name "db2.schools"
    end
    

    这有帮助吗?

    【讨论】:

      猜你喜欢
      • 2018-09-15
      • 1970-01-01
      • 2015-06-28
      • 2021-12-24
      • 1970-01-01
      • 2011-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多