Commit 25900c760b08519d1b23f0965efe67a5c6fab54a

Authored by Mehul Kar
1 parent d3c5df9d

add the ability to reindex all models in one rake command

Showing 2 changed files with 26 additions and 4 deletions   Show diff stats
@@ -398,8 +398,15 @@ Product.search "milk", load: false @@ -398,8 +398,15 @@ Product.search "milk", load: false
398 398
399 3. Deploy and reindex 399 3. Deploy and reindex
400 400
  401 + You can reindex a particular class:
  402 +
  403 + ```ruby
  404 + rake searchkick:reindex:class[Product] # or Product.reindex in the console
  405 + ```
  406 +
  407 + Or you can reindex all models at the same time:
401 ```ruby 408 ```ruby
402 - rake searchkick:reindex CLASS=Product # or Product.reindex in the console 409 + rake searchkick:reindex:all
403 ``` 410 ```
404 411
405 4. Once it finishes, replace search calls w/ searchkick calls 412 4. Once it finishes, replace search calls w/ searchkick calls
lib/searchkick/tasks.rb
@@ -2,8 +2,23 @@ require "rake" @@ -2,8 +2,23 @@ require "rake"
2 2
3 namespace :searchkick do 3 namespace :searchkick do
4 desc "re-index elasticsearch" 4 desc "re-index elasticsearch"
5 - task :reindex => :environment do  
6 - klass = ENV["CLASS"].constantize  
7 - klass.reindex 5 + namespace :reindex do
  6 + desc "reindex a Model by passing it as an argument"
  7 + task :class, [:klass] => [:environment] do |t, args|
  8 + begin
  9 + args[:klass].constantize.reindex
  10 + rescue
  11 + puts "#{args[:klass]} model not found"
  12 + end
  13 + end
  14 +
  15 + desc "reindex all models"
  16 + task :all => [:environment] do
  17 + Dir[Rails.root + "app/models/**/*.rb"].each { |path| require path }
  18 + models = ActiveRecord::Base.descendants.map(&:name)
  19 + models.each do |model|
  20 + model.constantize.reindex if model.respond_to?(:search)
  21 + end
  22 + end
8 end 23 end
9 end 24 end