# Guarding noticed Deliveries Against Deleted Records

> When a Booking disappears between enqueue and delivery, noticed's async jobs crash on nil.starts_at. Here's the guard and the test pattern to match.

- Author: Curtis Miller
- Published: 2026-11-18
- Categories: rails, debugging, testing, gotchas
- Canonical URL: https://millarian.com/posts/noticed-gem-nil-record-async-delivery/

Production lit up with thousands of `NoMethodError: undefined method 'starts_at' for nil`, all from an SMS notifier. The app uses the [noticed](https://github.com/excid3/noticed) gem (v2) to send notifications by email, push, and SMS. The notifier looked fine. The booking it referenced had been deleted.

## What was happening

The notifier built the SMS body from the booking:

```ruby
def sms_options(notification)
  super.merge(
    body: "You're booked for #{I18n.l notification.record.starts_at}.",
    to: notification.recipient.phone_number
  )
end
```

Deliveries run in background jobs. Between enqueueing the notification and running the SMS job, the user deleted their booking, so `notification.record` was nil. The job retried over and over, and one deleted booking turned into a wall of errors.

## The fix

noticed checks each delivery's `if:` condition inside the job, when it runs. That's the moment you know whether the record still exists. A base notifier can add the check to every channel:

```ruby
class ApplicationNotifier < Noticed::Event
  def self.deliver_by(name, options = {})
    super do |config|
      yield config if block_given?

      original_if = config[:if]
      config.if = lambda do
        recipient.present? &&
          (event.record_id.nil? || record.present?) &&
          (original_if.nil? || instance_exec(&original_if))
      end
    end
  end
end
```

Checking `record_id` matters. Some notifications never have a record, and those should still go out. If `record_id` is set but `record` is nil, the record was deleted, so the delivery is skipped. No error, no retry.

## Testing it

To reproduce the bug in a test, perform the jobs twice with the delete in between:

```ruby
BookingNotifier.with(record: booking).deliver(user)
perform_enqueued_jobs # EventJob enqueues the delivery jobs
booking.destroy
perform_enqueued_jobs # delivery jobs run with the record gone
```

## Takeaway

Records can disappear before a background delivery runs, so check for them when the job runs, not when it's enqueued.
