Tags

redhat
employment
ripple
interfaces
ncurses
ruby
refs
filesystems
retro gaming
raspberry pi
sinatra
3d printing
nethack
gcc
compiler
fedora
virtfs
project
gaming
vim
grep
sed
aikido
philosophy
splix
android
lvm
storage
bitcoin
projects
sig315
miq
db
polisher
meditation
hopex
conferences
omega
simulator
bundler_ext
rubygems
book review
google code in
isitfedoraruby
svn
gsoc
design patters
jsonrpc
rjr
aeolus
ohiolinuxfest
rome
europe
travel
brno
gtk
python
puppet
conference
fudcon
snap
html5
tips
ssh
linux
hardware
libvirt
virtualization
engineering expo
cloud
rpm
yum
rake
redmine
plugins
screencasting
jruby
fosscon
pidgin
gnome-shell
distros
notacon
presentation
rails
deltacloud
apache
qmf
passenger
syrlug
hackerspace
music
massive attack
crypto
backups
vnc
xsd
rxsd
x3d
mercurial
ovirt
qpid
webdev
haikus
poetry
legaleese
jquery
selenium
testing
xpath
git
sshfs
svg
ldap
autotools
pygtk
xmlrpc
slackware

Nov 3 2009 ruby rails

Difference between delete and destroy in ActiveRecord

This is well documented, but I keep running into the same issue and never learn from my mistakes. ;-)

When you invoke ‘destroy’ or ‘destroy_all’ on an ActiveRecord object, the ActiveRecord ‘destruction’ process is initiated, it analyzes the class you’re deleting, it determines what it should do for dependencies, runs through validations, etc.

When you invoke ‘delete’ or ‘delete_all’ on an object, ActiveRecord merely tries to run the ‘DELETE FROM tablename WHERE conditions’ query against the db, performing no other ActiveRecord-level tasks.

This also holds true for the :dependent option passed into the ActiveRecord::Association methods (belongsto, hasone, hasmany, hasandbelongsto_many)

Thus if you have a circular dependency between two model classes, and you want to delete both related records when one is deleted, one of the :dependent clauses must be :destroy and the other :delete. if both are set to :destroy you’ll have an infinite loop resulting in a “SystemStackError: stack level too deep” exception.

For example

class Person < ActiveRecord::Base
  has_one :address, :dependent => :destroy
  validate_presence_of :address
end

class Address < ActiveRecord::Base
  belongs_to :person, :dependent => :delete
  validates_presence_of :person
end

With this scenario, you are free to add a foreign key constraint to the person_id field of the addresses table and everything will still behave as expected. Best of luck.