Rails sunspot reindexing specific schema

111 Views Asked by At

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?

1

There are 1 best solutions below

1
shuberman On

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.