How to deal with `uninitialized constant` after deleting polymorphic ActiveRecord model

Viewed 110

We have a model like this:

class Notification < ApplicationRecord
  belongs_to :notifiable, polymorphic: true 
end

We’re getting uninitialized constant PatientVital after the model was deleted and table dropped. An action tries to iterate over all the notifiable records, and the ones with notifiable_type: PatientVital are now orphaned.

Notification.where(notifiable_type: 'PatientVital')

The data needs to persisted. Seems like a gotcha using ActiveRecord polymorphic. What's the best way to handle/prevent this when deleting a model who is a polymorphic type name?

1 Answers

Use Notification.where(notifiable_type: PatientVital) and your code will raise an error when you delete the class, so you can react earlier that you need to do something about the records with that class.

Related