Earlier when I tried to destroy a record from a model I was getting a Foreign key constraint error, so I added the dependent: :destroy
option in the relationships. This is how the relationships look like now:
class Package < ActiveRecord::Base
has_one :package_event, dependent: :destroy
has_one :tag_package, dependent: :destroy
has_one :current_bin, :through => :tag_package
has_many :tag_packages, lambda{ with_deleted }, dependent: :destroy
has_one :tag, :through => :tag_package
has_one :tag_type, :through => :tag
has_one :tag_issuer, :through => :tag
has_many :scans, lambda{ distinct }, :through => :tag
But now when I am trying to destroy a record from the model I am getting an ActiveRecord::RecordNotDestroyed and it is not showing the error message so I am not sure what is the reason behind this error.
>> Package.first.destroy!
=> ActiveRecord::RecordNotDestroyed (Failed to destroy the record)
I am suspecting this has something to do with the has_many_through
relation that is going on. Does anyone know how to fix this ?
You can rescue the error (rescue ActiveRecord::RecordNotDestroyed => error) and look at error.record.errors.
I found the solution from this answer: https://stackoverflow.com/a/53872915/4785305
It could be you have a before_destroy callback preventing one of the associated records from being destroyed.