C
C
CyFox2015-06-28 22:26:14
Ruby on Rails
CyFox, 2015-06-28 22:26:14

Ruby on Rails how to display a message to the user when deleting a record validates?

There are two models that are not related to each other, let's call them model1 and model2. Both models do not have their own controllers, and actions with model1 occur through accepts_nested_attributes_for of another model, model0. Before deleting a record from model1, you need to check for the presence of records in model2 and, if there are records in model2, prohibit deleting the record from model1.
Normal validations do not work when deleted. If you call your validation through before_destroy and return false in it, the exception will work and the record will not be deleted. This looks like a rails error and in the console we see ActiveRecord::RecordNotDestroyed (ActiveRecord::RecordNotDestroyed), and therefore, the error message does not reach the user.
I need, when deleting a record from model1, check for records in model2 and if they are, display a message to the user and not delete the record.
looked at stackoverflow.com/questions/123078/how-do-i-valida... , all options from here do not display messages, and the option with def before_destroy... as I understand it, works only for related models and is called only with dependent: : destroy. Couldn't find better advice.
I hope I wrote clearly :)
Thank you

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
thepry, 2015-06-29
@thepry

Before deleting a record from model1, you need to check for the presence of records in model2 and, if there are records in model2, prohibit deleting the record from model1.

has_many :model2s, dependent: :restrict
Maybe add an error message already. Need to check.
Apparently you are using destroy!instead destroy
Error message in the validation method can be added.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question