Old Monk
Old Monk

Reputation: 35

Cascade delete model in rails

class Car < ActiveRecord::Base
end

class City < ActiveRecord::Base
  has_many :cars_available, dependent: :destroy
end

class CarsAvailable < ActiveRecord::Base
  belongs_to :car
  belongs_to :city
end

I have two models Car and City, and a third model CarsAvailable which stores which particular cars are available in a particular City.

How to set a DESTROY association between a Car and CarsAvailable so that when a Car is removed then corresponding CarsAvailable entry also get deleted.

I figured it out for City but a little ambiguous how to apply it to Car.

Upvotes: 0

Views: 38

Answers (1)

Uzbekjon
Uzbekjon

Reputation: 11813

This will do the trick:

class Car < ActiveRecord::Base
  has_many :cars_available, dependent: :destroy
end

Add association to your Car and tell it to destroy association, just like you did with City.

Upvotes: 2

Related Questions