Home > database >  Update record in before_destroy and prevent its destruction
Update record in before_destroy and prevent its destruction

Time:09-29

I am using Rails 3.2, Ruby 1.9.3.

I need to prevent a record from being destroyed and update it in the before_destroy callback.

Given two classes with the following associations

class Course:
  has_many :attendants
  ...

class Attendant:
  belongs_to :course
  before_destroy :dont_really_destroy
  ...

I got a before_destroy callback in Attendant:

def dont_really_destroy
  update_attribute :deleted_at, Time.now 
  false
end

The callback does in fact prevent the delete when I call the destroy method. However, the record is not updated. It seemed reasonable since I by returning false I might be aborting any update (I tried with update_column as well). However, somehow, it does work as expected when the attendant record is "destroyed" from its association's (Course) form, by setting a _destroy form element. The record is correctly updated with deteled_at set, and not destroyed.

I've tried debugging to see the if the instances are different when I try to destroy from the course form vs directly destroying the attendant but I cannot see any differences.

When I do it via the course form, the record is updated like this:

course.assign_attributes(params[:course], :without_protection => true)
...
course.save

CodePudding user response:

Hi instead of using callbacks here, why don't you simply update the destroy action?

 #AttendantsController.rb
 def destroy
   update_attribute :deleted_at, Time.now
   head :ok
 end

And you default scope in your model

class Attendant:
  belongs_to :course
  default_scope -> { where(deleted_at: nil) }
  ...

Hope this will help you.

CodePudding user response:

You could also use ActAsParanoid Gem which introduces soft deletion for rails. https://github.com/ActsAsParanoid/acts_as_paranoid

  • Related