Rails 3 - 具有连接条件的多个数据库 [英] Rails 3 - Multiple database with joins condition
问题描述
我的环境:Ruby 1.9.2p290,Rails 3.0.9和RubyGem 1.8.8
多个数据库。
情况是这样:我有两个模型连接两个不同的数据库,并建立彼此之间的关联。
数据库连接在每个模型中指定,看起来像
ActiveRecord :: Base
self.establish_connectionlab
belongs_to:patient
end
class Patient< ActiveRecord :: Base
self.establish_connectionmain
has_many:visits
end
遇到以下情况时出现错误
@visits = Visit.joins(:patient)
错误:Mysql2 ::错误:表'lab.patients'不存在:SELECT 访问
。* FROM 访问
INNER JOIN 患者
ON 患者。
id
IS NULL
这里'patients'表位于'main'和'visits'表在'lab'数据库
我怀疑当执行代码,Rails正在考虑'病人'表是'实验室'数据库[其中包含访问表的一部分。
self.table_name_prefix
以显式返回数据库名称。 class Visit< ActiveRecord :: Base
def self.table_name_prefix
renv = ENV ['RAILS_ENV'] || ENV ['RACK_ENV']
(renv.empty??lab。:lab _#{renv}。)
end
self.establish_connectionlab
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_connectionmain
has_many:visits
end
我仍在处理所有细节它涉及到指定加入条件,但我希望这有助于。
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)
Errors: Mysql2::Error: Table 'lab.patients' doesn't exist: SELECT visits
.* FROM visits
INNER JOIN patients
ON patients
.id
IS NULL
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].
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屋!