Search code examples
ruby-on-railsrubymulti-tenantmultiple-databases

Rails application with multiple database connections


I have a single Rails instance with a multiple database connection which serves two different services. Let's say it serves service A and service B. Service A requires connection to database A' and Service B requires connection to database B'. Most of the tables in A' and B' are identical (table name, schema). Eg. Database A' and B' both have a table User with identical schema. Currently my model for user looks like:

class User_A < ABase #connects to A'
    self.table_name = "user"

    def foo
      ...
    end

end

class User_B < BBase #connects to B'
    self.table_name = "user"

    def foo
      ...
    end

end

Inside controller I have to do something like:

if is_A?
 user = User_A.find(123)
else
 user = User_B.find(123)
end

Is there any better way to handle such situation in rails which would minimize code repetition?


Solution

  • Multitenancy for Rails and ActiveRecord
    

    Apartment provides tools to help you deal with multiple tenants in your Rails application. If you need to have certain data sequestered based on account or company, but still allow some data to exist in a common tenant, Apartment can help

    gem 'apartment'
    

    Apartment gem This gives you access to use multiple db in most easy way as possible.

    Apartment::Tenant.switch db_name
    

    Now You can access like this

    class User < ABase
    
        def foo
          Apartment::Tenant.switch db_a
          #Do what you update in db_a
    
          Apartment::Tenant.switch db_b
          #Do what you update in db_b
        end
    
    end