Is there a Rails 4 circular dependent: :destroy workaround?

后端 未结 2 1040
甜味超标
甜味超标 2021-02-13 19:42

As an example for the circular dependent: :destroy issue:

class User < ActiveRecord::Base
  has_one: :staff, dependent: :destroy
end

class Staff         


        
相关标签:
2条回答
  • 2021-02-13 20:09

    If one side of the cycle only has that one callback, you can replace one of the dependent: :destroy with dependent: :delete

    class User < ActiveRecord::Base
      # delete prevents Staff's :destroy callback from happening
      has_one: :staff, dependent: :delete
      has_many :other_things, dependent: :destroy
    end
    
    class Staff < ActiveRecord::Base
      # use :destroy here so that other_things are properly removed
      belongs_to :user, dependent: :destroy
    end
    

    Worked great for me, as long as one side doesn't need other callbacks to fire.

    0 讨论(0)
  • 2021-02-13 20:23

    I faced this issue as well, and came up with a solution that isn't pretty but works. Essentially, you'd just use a destroy_user that's similar to destroy_staff.

    class User < ActiveRecord::Base
      has_one: :staff
    
      after_destroy :destroy_staff
    
      def destroy_staff
        staff.destroy if staff && !staff.destroyed?
      end
    end
    
    class Staff < ActiveRecord::Base
      belongs_to :user
    
      after_destroy :destroy_user
    
      def destroy_user
        user.destroy if user && !user.destroyed?
      end
    end
    
    0 讨论(0)
提交回复
热议问题