0

We have a model ChatRoom which has many messages, the ChatRoom implements add_message and receives the parameters for the message along with a boolean notify which specifies whether we should send an email or not for the created message.

We publish :message_created after the message is created, however in our subscriber we receive an ActiveRecordNotFound error however there is an ID present meaning that the message is persisted in the database.

We have a couple potential fixes however we want to understand the problem and it's cause.

class ChatRoom < ApplicationRecord
  has_many :messages, -> { order(:created_at) }

  def add_message(args)
    content = args.fetch(:content)
    creator = args.fetch(:creator)
    notify = args.fetch(:notify, false)

    message = self.messages.create!(content: content, creator: creator)
    publish(:message_created, message_id: message.id, notify: notify)
  end
end
class MessageCreated::MailChatSubscriber < ApplicationSubscriber
  def message_created(args)
    message = Message.find(args.fetch(:message_id))
    notify = args.fetch(:notify)

    Messages::Organizers::SendChatResponseMail.call(
      message: message,
      notify: notify
    )
  end
end

The error is presented below: Couldn't find Message with 'id'=575565

Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
  • 1
    Is it an option to pass the complete message instead of just the id? You got to use the full message in the `MessageCreated` class anyway. It might be some kind of caching or concurrency problem. – Jeroen Verfaillie Aug 24 '22 at 09:51
  • We though of doing that but it is considered bad practice to pass ActiveRecord Models to subscribers instead of primitives. – Brandon Teixeira Aug 24 '22 at 10:28
  • 1
    Found the answer in the following question https://stackoverflow.com/questions/73631559/sidekiq-not-finding-id-even-after-transaction?noredirect=1#comment130025259_73631559 – Brandon Teixeira Sep 07 '22 at 08:20

0 Answers0