<model>.establish_connection configurations['legacy']<\/pre>\nCreate Your ‘Through’ Model<\/h3>\n
Now a normal ‘has_many through’ just plain won’t work between models attached to two different databases but a normal has_many will. So we can create ‘has_many through’ functionality in the following way:<\/p>\n
Set up your ‘through’ model on either database. It really doesn’t matter which and set it to ‘belong_to’ your two main models.<\/p>\n
Set both main models to ‘has_many’ of your ‘through’ model.<\/p>\n
Create Your ‘Through’ Relationship<\/h3>\n
Use the following code in each of your main models to mimic the ‘has_many through’ association. In this example I’m using ‘orders’ and ‘users’ and my ‘through’ table is ‘order_users’:<\/p>\n
In ‘order’<\/p>\n
def users\n user = []\n order_users.each do |ou|\n user << ou.user\n end\n user\nend<\/pre>\nIn ‘user’<\/p>\n
def orders\n order = []\n order_users.each do |ou|\n order << ou.user\n end\n order\nend<\/pre>\nAnd you’re done. Now the relationship will work just like any other ‘has_many through’.<\/p>\n","protected":false},"excerpt":{"rendered":"
So recently I had the challenge of creating a ‘has_many through’ relationship across two databases. “Why would you do this?” you may ask. Well quite simply I am in a team building a new data management system to sit on top of a legacy system with its legacy database, we want to create something similar […]<\/p>\n","protected":false},"author":13,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[9,25,3],"tags":[],"_links":{"self":[{"href":"https:\/\/www.setfiremedia.com\/blog\/wp-json\/wp\/v2\/posts\/102"}],"collection":[{"href":"https:\/\/www.setfiremedia.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.setfiremedia.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.setfiremedia.com\/blog\/wp-json\/wp\/v2\/users\/13"}],"replies":[{"embeddable":true,"href":"https:\/\/www.setfiremedia.com\/blog\/wp-json\/wp\/v2\/comments?post=102"}],"version-history":[{"count":1,"href":"https:\/\/www.setfiremedia.com\/blog\/wp-json\/wp\/v2\/posts\/102\/revisions"}],"predecessor-version":[{"id":690,"href":"https:\/\/www.setfiremedia.com\/blog\/wp-json\/wp\/v2\/posts\/102\/revisions\/690"}],"wp:attachment":[{"href":"https:\/\/www.setfiremedia.com\/blog\/wp-json\/wp\/v2\/media?parent=102"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.setfiremedia.com\/blog\/wp-json\/wp\/v2\/categories?post=102"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.setfiremedia.com\/blog\/wp-json\/wp\/v2\/tags?post=102"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}