Ever heard of
transaction_include_any_action?([:action])? You may never need to use this specialized part of ActiveRecord, but I thought I would shed some light on it anyway.
Recently, I was writing a module that helped incorporate several models into Elasticsearch. Concerns::Searchable, as I named it, helps create mappings for models, provides a base method for specialized searches, and also has an
after_commit hook to index records. I first looked into ActiveRecord::Transactions to customize when a record is indexed into Elasticsearch.
module Concerns module Searchable extend ActiveSupport::Concern included do include Elasticsearch::Model after_commit :update_elasticsearch_index ... def update_elasticsearch_index if transaction_include_any_action?([:destroy]) || (transaction_include_any_action?([:update]) && self.archived?) ElasticsearchIndexWorker.perform_async(:delete, self.id) else ElasticsearchIndexWorker.perform_async(:index, self.id) end end end end end
What I wanted was for Elasticsearch to delete records that were deleted in Postgres OR “archived”. That way, when a user goes to search for a record, they won’t accidentally get results from “archived” records that are being kept in Postgres for other purposes. Using ActiveRecord::Transactions helped me customize the logic for indexing after_commit.
NOTE: One small hiccup you may encounter is that the argument passed to the method has to be an array.
This is okay:
This is not: