I want to raise an exception or error when the associated record exists when deleting a record. This is a situation where the parent element should not be erased if it is used in a foreign key.
When I try to delete it, a Ruby error screen appears.
It was because there was no definition of the behavior for the model associated with
The migration file
foreign key: True was not enough.
It was solved by writing the
dependent option in the
Write the following for the model.
#Model called contract class Contract < ApplicationRecord has_many :...., dependent: :restrict_with_error end
dependent:: restrict_with_error after the association description, it was possible to display the error when
destory cannot be done.
The following conditions have been met and resolved! ..
#Controller of model called contract def destroy contract = Contract.find(params[:id]) if contract.destroy redirect_to contract_path, notice: "Deleted the selected contract" else redirect_to contract_path, alert: "Cannot be deleted because it is in use" end end