Search code examples
ruby-on-railsmongoidruby-on-rails-6apartment-gem

Cloning Mongoid document in ruby on rails from one tenant to another tenant


I am using ruby 2.7 and rails 6.0.3.2, mongoid gem 7.1.0 with ros-paartment gem 2.7.2. What I am trying to do? I have different tenants created using ros-apartment gem. I have populated data on admin tenant. In admin tenant, I have around 12 DB tables, here DB used is mongo. Now What I want is whenever a new tenant is created, I want to copy all the content of a few tables from admin tenant to newly created tenant. Suppose, say I have 12 tables, I want to populate 9 tables to newly created tenant from admin tenant. Is there any solution to achieve this?


Solution

  • what you could try is

    after_create_tenant :copy_from_admin_tenant
    
    
    def copy_from_admin_tenant
     data = Apartment::Tenant.switch('admin_tenant') { admin_data = Model.all.as_json}
     data.each {|x| Model.create(x)}
    end