0

The application I'm currently working on requires me to access multiple data sources from within a single model. I want to know what's the best way to accomplish it. Can I do something like the following?

class SomeModel < ActiveRecord::Base
  establish_connection :data_source1
  # Get some data from data_source1 and store in a instance variable

  establish_connection :data_source2
  # Get some data from data_source2 and store in a instance variable
end

Appreciate for your suggestions.

Just a learner
  • 26,690
  • 50
  • 155
  • 234

1 Answers1

0

This is a super bad idea as @jvillian has said. What you want here is two different models each connected to their respective data source, something ActiveRecord does allow by default.

That part can be a bit tricky but won't confuse ActiveRecord.

The big issue here is it prefers to cache the schema when it connects and persists that for the life of the process. If the databases differ in any way you'll have chaos, plus if you keep switching the connection you may completely mess up the transaction planner which has to take into account which models live in which database for rollback purposes.

Community
  • 1
  • 1
tadman
  • 208,517
  • 23
  • 234
  • 262