rubysherpas / paranoia

acts_as_paranoid for Rails 5, 6 and 7
Other
2.88k stars 528 forks source link

`before_destroy` broken on model with has_many association #219

Open favour121 opened 9 years ago

favour121 commented 9 years ago

If before_destroy returns false on a model that has_many associated models with dependent: :destroy, the associations are destroyed but the model itself isn't destroyed.

Example Code:

class Subject < ActiveRecord::Base acts_as_paranoid belongs_to :elective_group end

class ElectiveGroup < ActiveRecord::Base acts_as_paranoid has_many :subjects, dependent: :destroy

before_destroy :deletable?

def deletable? false end end

elective_group = ElectiveGroup .create(params) elective_group.subjects.create(params);

add more subjects to elective_group

elective_group.destroy

elective_group isn't destroyed as expected, but all associated subjects get destroyed.

Suggestion

Code should either ensure before_destroy doesn't return false before destroying associations, or Rollback all destroyed associations using Transactions.

arathunku commented 9 years ago

I had similar problem but with has_one and solved that by prepending my callback.

  before_destroy :destroyable?, unless: :destroy_force, prepend: true

  def destroyable?
    false # or throw(:abort)  - https://github.com/rails/rails/pull/17227
  end
mikdiet commented 8 years ago

I have similar problem.

In fact, associations are destroyed before before_destroy callbacks, so if you try to access these associations in callback, they are not exist already.

tobeee commented 7 years ago

@Mik-die - Do you know if there is anyway around that? Did prepend solve it?

mikdiet commented 7 years ago

@tobeee this happened so long ago, I did not remember how I solved it, sorry..

tobeee commented 7 years ago

Just adding prepend: true sorted it out!

On Tue, Mar 28, 2017 at 5:23 PM, Mikhail Dieterle notifications@github.com wrote:

@tobeee https://github.com/tobeee this happened so long ago, I did not remember how I solved it, sorry..

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/rubysherpas/paranoia/issues/219#issuecomment-289825070, or mute the thread https://github.com/notifications/unsubscribe-auth/ABxI8KYu8lvLUZ1YzCIN9qzFm9DV1gAmks5rqTP7gaJpZM4Dx2Tv .

-- Toby Green