0

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?

Mexxer
  • 1,699
  • 5
  • 27
  • 40

1 Answers1

0

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
Nick Kugaevsky
  • 2,935
  • 1
  • 18
  • 22