Michael Irwin
Michael Irwin

Reputation: 3149

ActiveRecord :dependent confusion

I have the following AR models defined:

class Venue < ActiveRecord::Base
  has_many :events
end

class Act < ActiveRecord::Base
  has_many :events
end

class Event < ActiveRecord::Base
  belongs_to :venue
  belongs_to :act
end

What I want is if I delete a Venue or Act, any associated Events are also deleted. But if I delete an Event, the associated Venue and Act are NOT deleted. I've tried various :dependent variations, but nothing seems to be working.

This seems so simple. What am I missing?

Upvotes: 0

Views: 164

Answers (2)

Michael Irwin
Michael Irwin

Reputation: 3149

I figured out the problem. I had to call destroy instead of delete on the parent object. The docs don't really make that clear.

Upvotes: 1

Dogbert
Dogbert

Reputation: 222408

This works for me. Deleting Venue/Act deletes all events it had, while deleting an event has no effect on Venue/Act it belonged to.

class Venue < ActiveRecord::Base
  has_many :events, :dependent => :destroy
end

class Act < ActiveRecord::Base
  has_many :events, :dependent => :destroy
end

class Event < ActiveRecord::Base
  belongs_to :venue
  belongs_to :act
end

Upvotes: 1

Related Questions