Go back to the main page

Implementing destroy validate false in Rails

This article is over 2 years old. Proceed with caution.

Regards ♨ – Minimul

 

Not sure why Rails doesn't have a record.destroy(:validate => false) as there is this option within the save method.

Notes:

  • Tested in Rails 3.2
class User < ActiveRecord::Base
  # Override destroy to avoid validation callbacks
  # but still run all other destroy callbacks as normal
  # update_attribute, update_column, and touch do not 
  # run validate callbacks
  def destroy
    run_callbacks :destroy do
      update_attribute(:deleted_at, Time.zone.now)
      # You can also put 'touch(:deleted_at)'
      # or 'update_column(:deleted_at, Time.zone.now)'
      # but be aware that they don't effect 'record.changed?'
    end
  end
end
Comment on this article?