From 7f724c219bde988682caa4e90ed5f0141bfab2dc Mon Sep 17 00:00:00 2001 From: Andrew Kane Date: Wed, 12 Feb 2014 23:42:17 -0800 Subject: [PATCH] Use after_commit hook to protect against data inconsistencies - closes #111 --- README.md | 31 ++++++++++++++++++++----------- lib/searchkick/model.rb | 8 ++++++-- test/index_test.rb | 13 +++++++++++++ 3 files changed, 39 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 960f653..1e9823e 100644 --- a/README.md +++ b/README.md @@ -657,25 +657,20 @@ class Product < ActiveRecord::Base end ``` -Reindex conditionally +Asynchronous reindexing + +**Note:** Use `after_commit` for ActiveRecord and `after_save` and `after_destroy` for Mongoid ```ruby class Product < ActiveRecord::Base searchkick callbacks: false # add the callbacks manually - after_save :reindex, if: proc{|model| model.name_changed? } # use your own condition - after_destroy :reindex -end -``` -Asynchronous reindexing - -```ruby -class Product < ActiveRecord::Base - searchkick callbacks: false + # ActiveRecord - one callback + after_commit :reindex_async - # add the callbacks manually + # Mongoid - two callbacks after_save :reindex_async after_destroy :reindex_async @@ -686,6 +681,20 @@ class Product < ActiveRecord::Base end ``` +Reindex conditionally + +**Note:** Use with caution - (transaction rollbacks can cause data inconstencies)[https://github.com/elasticsearch/elasticsearch-rails/blob/master/elasticsearch-model/README.md#custom-callbacks] with this feature + +```ruby +class Product < ActiveRecord::Base + searchkick callbacks: false + + # add the callbacks manually + after_save :reindex, if: proc{|model| model.name_changed? } # use your own condition + after_destroy :reindex +end +``` + Reindex all models (Rails only) ```sh diff --git a/lib/searchkick/model.rb b/lib/searchkick/model.rb index df4d59e..66142fd 100644 --- a/lib/searchkick/model.rb +++ b/lib/searchkick/model.rb @@ -19,8 +19,12 @@ module Searchkick extend Searchkick::Reindex include Searchkick::Similar - after_save :reindex, if: proc { self.class.search_callbacks? } - after_destroy :reindex, if: proc { self.class.search_callbacks? } + if respond_to?(:after_commit) + after_commit :reindex, if: proc{ self.class.search_callbacks? } + else + after_save :reindex, if: proc{ self.class.search_callbacks? } + after_destroy :reindex, if: proc{ self.class.search_callbacks? } + end def self.enable_search_callbacks class_variable_set :@@searchkick_callbacks, true diff --git a/test/index_test.rb b/test/index_test.rb index a796594..be054e9 100644 --- a/test/index_test.rb +++ b/test/index_test.rb @@ -32,4 +32,17 @@ class TestIndex < Minitest::Unit::TestCase assert_equal ["Dollar Tree"], Store.search(query: {match: {name: "Dollar Tree"}}).map(&:name) end + if defined?(ActiveRecord) + + def test_transaction + Product.transaction do + store_names ["Product A"] + raise ActiveRecord::Rollback + end + + assert_search "product", [] + end + + end + end -- libgit2 0.21.0