How do I prevent deletion of parent if it has child records?

前端 未结 4 911
一生所求
一生所求 2020-12-24 01:00

I have looked through the Ruby on Rails guides and I can\'t seem to figure out how to prevent someone from deleting a Parent record if it has Children. For example. If my

4条回答
  •  忘掉有多难
    2020-12-24 01:22

    class Customer < ActiveRecord::Base
      has_many :orders, :dependent => :restrict # raises ActiveRecord::DeleteRestrictionError
    

    Edit: as of Rails 4.1, :restrict is not a valid option, and instead you should use either :restrict_with_error or :restrict_with_exception

    Eg.:

    class Customer < ActiveRecord::Base
      has_many :orders, :dependent => :restrict_with_error
    

提交回复
热议问题