Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/gwt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何跨2个数据库进行即时加载?_Ruby On Rails_Rails Activerecord - Fatal编程技术网

Ruby on rails 如何跨2个数据库进行即时加载?

Ruby on rails 如何跨2个数据库进行即时加载?,ruby-on-rails,rails-activerecord,Ruby On Rails,Rails Activerecord,我必须与遗留数据库中的某些数据进行交互,该数据库不是我的应用程序的一部分。我需要从两个源加载数据,而不会导致n+1查询 东西。rb class Thing # Lives in my applications DB belongs_to :other_thing end class OtherThing establish_connection(:other_database) has_many :things end 其他东西。rb class Thing # Live

我必须与遗留数据库中的某些数据进行交互,该数据库不是我的应用程序的一部分。我需要从两个源加载数据,而不会导致n+1查询

东西。rb

class Thing
  # Lives in my applications DB
  belongs_to :other_thing
end
class OtherThing
  establish_connection(:other_database)
  has_many :things
end
其他东西。rb

class Thing
  # Lives in my applications DB
  belongs_to :other_thing
end
class OtherThing
  establish_connection(:other_database)
  has_many :things
end
东西。包括(:其他东西)
不起作用,因为其他内容位于不同的模式中

Thing.all.map(&:其他东西)
可以工作,但会生成n+1个查询

到目前为止,这是我想到的最好的:

things = Thing.all
other_things = OtherThing.find(things.map(&:other_thing_id))
things = things.map{|t| t.other_thing = other_things.select{|ot| ot.id == t.other_thing_id}.first; t }

这只会导致两个查询,但我认为必须存在更好的解决方案。

您可以使用
预加载
来实现这一点:

Think.preload(:other_thing)
与上面所说的相反,它不像
#include
那样工作