Search code examples
ruby-on-railselasticsearchtiredestroy

Delete Tire search index on destroy


I implemented elasticsearch and it seems to work fine except for when I want to delete a record of something. In my controller destroy method I can't seem to delete the index without doing rake environment tire:import CLASS=Stream FORCE=true

 def destroy
   #@stream = Stream.friendly.find(params[:id])
   #Stream.tire.index(@stream).delete
   #@stream.destroy

    @stream.destroy
    system "rake environment tire:import CLASS=Stream FORCE=true"

    respond_to do |format|
      format.html { redirect_to streams_url, notice: 'Stream was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

If I use the commented out code I get the error: ActiveRecord::RecordNotFound (Couldn't find all Streams with 'id': (1, 2, 3, 4) (found 2 results, but was looking for 4)):

How are you supposed to delete the index properly along with @stream?

EDIT Model code

  class Stream < ActiveRecord::Base

  extend FriendlyId
  friendly_id :title

  include Tire::Model::Search
  include Tire::Model::Callbacks

  def self.search(params)
    tire.search(load: true) do
      query { string params[:query], default_operator: "AND" } if params[:query].present?
    end
  end

end

Solution

  • If you use Tire::Model::Callbacks module in your Stream model it should be deleted automatically.

    If you want to run it manually from controller following code should probably work.

    @stream.destroy
    @stream.tire.update_index