Skip to content

Instantly share code, notes, and snippets.

@tiagoamaro
Last active May 15, 2021 00:04
Show Gist options
  • Save tiagoamaro/aa8f776b3217f2974f69 to your computer and use it in GitHub Desktop.
Save tiagoamaro/aa8f776b3217f2974f69 to your computer and use it in GitHub Desktop.
searchkick-apartment-example-codes
class Post
searchkick index_name: -> { [Apartment::Tenant.current, model_name.plural, Rails.env].join('_') }
end
class Post
include SchemaSearchable
searchkick index_name: tenant_index_name
end
module SchemaSearchable
extend ActiveSupport::Concern
module ClassMethods
def tenant_index_name
-> { [Apartment::Tenant.current, model_name.plural, Rails.env].join('_') }
end
end
end
# `Searchkick.models` method is available on versions 0.8.6+
namespace :searchkick do
desc 'Reindex all models on all tenants'
task reindex_tenants: :environment do
Rails.application.eager_load!
Apartment::Tenant.each do |schema|
Apartment::Tenant.switch!(schema)
Searchkick.models.each do |model|
puts "Reindexing #{model.name} on #{schema}"
model.reindex
end
end
end
end
# If you're using Searchkick 0.8.5 or older versions, you should use its `@descendants` instance variable to get the models. Example:
namespace :searchkick do
desc 'Reindex all models on all tenants'
task reindex_tenants: :environment do
Rails.application.eager_load!
# You'll need to tell the rake task which tenant_names you are going to use
User.pluck(:database).each do |schema|
Apartment::Tenant.switch schema
(Searchkick::Reindex.instance_variable_get(:@descendents) || []).each do |model|
puts "Reindexing #{model.name} on #{schema}"
Apartment::Tenant.switch schema
model.reindex
end
end
end
end
@Xosmond
Copy link

Xosmond commented Jan 16, 2017

Hello, thank you for this, one question, will this make searchkick work properly? So can search for all records on shared tables and only on it records on normal tables?

@tiagoamaro
Copy link
Author

@Xosmond yes, Searchkick will continue to properly work. This does not affect Searchkick features at all, since it uses the "dynamic index name" feature it offers. (More on its reference docs: https://github.com/ankane/searchkick#reference).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment