ruby-on-railsrubyapartment-gem

Query different schemas data in a rails application for read+write


I have two rails application base1 and base2.

base1 uses db1 and have multiple tenants inside this database, its using apartment gem.

base2 is single tenant application and has database db2 as primary, and also uses data from db1.

Now the problem is, base2 application established connection to db1 and i can get the data db1 data in public tenant in base2 application.
How to get data from different schemas of db1 in base2 application?


Solution

  • As per discussions in comments.

    def self.with_schema(schema_name)
        class_name = self.name + schema_name.camelize
        table_name = self.table_name
        if !Object.const_defined?(class_name)
          Object.const_set(
            class_name, Class.new(self) do
              self.table_name = "#{schema_name}.#{table_name}"
            end
          )
        end
        class_name.constantize
      end
    

    Add this to your application record and you can do things like: Data.schema('schema_name').all