If a user wants to destroy a parent model record and it has children, I want to be able to show a custom error message.
Or maybe to hide the destroy button if a record has no children. How can I do this?
If a user wants to destroy a parent model record and it has children, I want to be able to show a custom error message.
Or maybe to hide the destroy button if a record has no children. How can I do this?
Place in your model something like this
class Parent < ActiveRecord:Base
has_many :children
before_destroy :check_children!
private # <--- Bottom of model
def check_children!
unless childrens.empty?
self.errors.messages[:children_present] = "Can't destroy parent cause children present!"
false
end
end
end