Check all associations before destroy in rails

后端 未结 2 719
礼貌的吻别
礼貌的吻别 2020-12-28 23:24

I have an important model in my application, with many associations. If I want to check all the references in a before_destroy callback, i\'d have to do something like:

2条回答
  •  攒了一身酷
    2020-12-28 23:30

    You can pass the :dependent => :restrict option to your has_many calls:

    has_many :models, :dependent => :restrict
    

    This way, you will only be able to destroy the object if no other associated objects reference it.

    Other options are:

    • :destroy - destroys every associated object calling their destroy method.
    • :delete_all - deletes every associated object without calling their destroy method.
    • :nullify - sets the foreign keys of the associated objects to NULL without calling their save callbacks.

提交回复
热议问题