Rails 3 - 具有连接条件的多个数据库 [英] Rails 3 - Multiple database with joins condition

查看:29
本文介绍了Rails 3 - 具有连接条件的多个数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的环境:Ruby 1.9.2p290、Rails 3.0.9 和 RubyGem 1.8.8

My environment: Ruby 1.9.2p290, Rails 3.0.9 and RubyGem 1.8.8

不幸的是,我遇到多个数据库时遇到问题.

unfortunately I have an issue when come across multiple database.

情况是这样的:我有两个模型连接到两个不同的数据库,并在彼此之间建立关联.每个模型中指定的数据库连接,看起来像

The situation is this: I have two model connect with two different database and also establishing association between each other. database connection specifying in each model, look likes

class Visit < ActiveRecord::Base
  self.establish_connection "lab"
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  self.establish_connection "main"
  has_many :visits
end

遇到以下场景时出现错误

I got an error when meet following scenario

@visits = Visit.joins(:patient)

错误:Mysql2::Error:表'lab.patients'不存在:SELECT visits.* FROM visits INNER JOIN patients ON patients.id IS NULL

Errors: Mysql2::Error: Table 'lab.patients' doesn't exist: SELECT visits.* FROM visits INNER JOIN patients ON patients.id IS NULL

这里的患者"表位于主"数据库中,访问"表位于实验室"数据库中我怀疑在执行代码时,Rails 是否认为患者"表是实验室"数据库 [其中包含访问"表] 的一部分.

Here 'patients' table is in 'main' database and 'visits' table in 'lab' database I doubt when executing the code, that Rails is considering 'patients' table is part of 'lab' database [which holds 'visits' table].

推荐答案

好吧,我不知道这是否是最优雅的解决方案,但我确实通过定义 self.table_name_prefix 显式返回数据库名称.

Well, I don't know if this is the most elegant solution, but I did get this to work by defining self.table_name_prefix to explicitly return the database name.

class Visit < ActiveRecord::Base
  def self.table_name_prefix
    renv = ENV['RAILS_ENV'] || ENV['RACK_ENV']
    (renv.empty? ? "lab." : "lab_#{renv}.")
  end

  self.establish_connection "lab"
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  def self.table_name_prefix
    renv = ENV['RAILS_ENV'] || ENV['RACK_ENV']
    (renv.empty? ? "main." : "main_#{renv}.")
  end

  self.establish_connection "main"
  has_many :visits
end

在指定连接条件方面,我仍在研究所有细节,但我希望这会有所帮助.

I'm still working through all the details when it comes to specifying the join conditions, but I hope this helps.

这篇关于Rails 3 - 具有连接条件的多个数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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