How to use dependent: :destroy in rails?

↘锁芯ラ 提交于 2019-11-28 07:22:06
Umar Khan

Add cascading delete to your EmpGroup model:

class EmpGroup < ActiveRecord::Base
   has_many :emp_group_members, :dependent => :delete_all
end

Or

Are you calling delete method? you should call destroy instead. Use .destroy

:dependent is one of the options available in belongs_to association

If you set the :dependent option to:

:destroy, when the object is destroyed, destroy will be called on its associated objects.
:delete, when the object is destroyed, all its associated objects will be deleted directly from the database without calling their destroy method.

Additionally, objects will be destroyed if they're associated with dependent: :destroy, and deleted if they're associated with dependent: :delete_all.

in has_many associations:

:destroy causes all the associated objects to also be destroyed
:delete_all causes all the associated objects to be deleted directly from the database (so callbacks will not execute)

you can try

 emp_member_1= @emp_group.emp_group_members.first
 ##delete associated record
 @emp_group.emp_group_members.delete(emp_member_1)

When you delete a group, are you using delete or destroy. - I've had this error before, and it was because I had a typo and was using .delete instead of .destroy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!