Ruby on rails 如何跨2个数据库进行即时加载?
我必须与遗留数据库中的某些数据进行交互,该数据库不是我的应用程序的一部分。我需要从两个源加载数据,而不会导致n+1查询 东西。rbRuby 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
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
那样工作