Michael Whitman wrote:
I have a Deck object and a Card object with their corresponding tables.
(You know a deck of cards.) When I destory a Deck it leaves orphaned
cards in the database. Is there a way to set up the objects with
ActiveRecord so that when a parent object is destoryed the child objects
are destroyed as well? My code below.
Take a look at the :dependent option for has_many associations:
:dependent - if set to :destroy all the associated objects are destroyed
alongside this object by calling their destroy method. If set to
:delete_all all associated objects are deleted without calling their
destroy method. If set to :nullify all associated objects? foreign keys
are set to NULL without calling their save callbacks. NOTE: :dependent
=> true is deprecated and has been replaced with :dependent => :destroy.
May not be set if :exclusively_dependent is also set.
So you want something like:
class Deck < ActiveRecord::Base
has_many :cards, :dependent => :destroy
class Card < ActiveRecord::Base