diff --git a/app/models/message/searchable.rb b/app/models/message/searchable.rb index e827c61..2cfe696 100644 --- a/app/models/message/searchable.rb +++ b/app/models/message/searchable.rb @@ -3,7 +3,8 @@ module Message::Searchable included do after_create_commit :create_in_index - after_update_commit :update_in_index, if: :body_saved? + before_update -> { @attachment_replaced = attachment_changes.key?("attachment") } + after_update_commit :update_in_index, if: :indexed_text_changed? after_destroy_commit :remove_from_index scope :search, ->(query) { joins("join message_search_index idx on messages.id = idx.rowid").where("idx.body match ?", match_terms(query)).ordered } @@ -22,9 +23,10 @@ module Message::Searchable execute_sql_with_binds "insert into message_search_index(rowid, body) values (?, ?)", id, plain_text_body end - # Boosts touch their message too: rewrite the index only when the body was saved. - def body_saved? - association(:rich_text_body).target&.saved_change_to_body? + # Boosts touch their message too: rewrite the index only when the body was saved or the attachment replaced. + # Active Storage clears attachment_changes in its own after_commit, before this one runs. + def indexed_text_changed? + association(:rich_text_body).target&.saved_change_to_body? || @attachment_replaced end def update_in_index diff --git a/test/models/message/searchable_test.rb b/test/models/message/searchable_test.rb index 3da41dd..eab5f73 100644 --- a/test/models/message/searchable_test.rb +++ b/test/models/message/searchable_test.rb @@ -37,6 +37,14 @@ class Message::SearchableTest < ActiveSupport::TestCase assert_equal [], rooms(:designers).messages.search("sharks") end + test "a new attachment replaces the old file name in the index" do + message = rooms(:designers).messages.create! attachment: fixture_file_upload("moon.jpg", "image/jpeg"), client_message_id: "moon", creator: users(:david) + + Message.find(message.id).update! attachment: fixture_file_upload("pixel.bmp", "image/bmp") + assert_equal [ message ], rooms(:designers).messages.search("pixel") + assert_equal [], rooms(:designers).messages.search("moon") + end + test "search results are returned in message order" do messages = [ "first cat", "second cat", "third cat", "cat cat cat" ].map do |body| rooms(:designers).messages.create! body: body, client_message_id: body, creator: users(:david)