2

I'm using rails-on-services/apartment this is a Multitenancy for Rails and ActiveRecord

my setup is every time I create a Tenant the gem automatically creates a specific schema for the new tenant.

every time I run the rails sunspot:reindex the record will not appear in the search level. but in ActiveRecord(ex.Client.all) the record is there.

my theory is the tenant I created is not reindexing. is there a way to reindex specific schema? or I'm missing something?

wiwit
  • 73
  • 1
  • 7
  • 26

1 Answers1

1

It appears that the problem is that when you run the rails sunspot:reindex command, the data for each tenant's schema isn't being reindexed. To fix this, you can create a custom Rake task that loops through each tenant and reindexes the data for each schema separately.

Follow these steps to create the Rake task:

  1. Create a new file called sunspot.rake in your Rails project's lib/tasks directory:

    #lib/tasks/sunspot.rake
    
    namespace :sunspot do
      desc "Reindex all tenants"
      task reindex_tenants: :environment do
         all_tenants = Tenant.all
         all_tenants.each do |current_tenant|
          Apartment::Tenant.switch(current_tenant.schema_name) do
            puts "Reindexing schema: #{current_tenant.schema_name}"
            Rake::Task["sunspot:reindex"].execute
          end
        end
      end
    end
    

This Rake task will iterate through all tenants, switch to the corresponding tenant's schema using Apartment::Tenant.switch, and then call the sunspot:reindex task to reindex the data for that schema.

  1. To run the newly created Rake task, enter the following command:

    rake sunspot:reindex_tenants
    

This command will reindex the data for all tenants' schemas separately, ensuring that the data for each schema is indexed correctly.

Remember to replace Tenant with the appropriate model name that represents your tenant in your application.

shuberman
  • 1,416
  • 6
  • 21
  • 38
  • 1
    thanks for the reply this helped to reindex all my tenants. unfortunately, the last tenant will be reindexed. will follow all the records of all my tenants. for example, Tenant1 has 10 records for Table 1. then Tenant2 has 3 records for Table 1. when I reindex all. Tenant2 will be the last reindex. when I load the Tenant1 Table1 records will appear 3 records only. – wiwit Mar 15 '23 at 06:27