Reputation: 513
I have the following model associations
Customer model
class Customer
has_many :readings
has_many :invoices
end
Reading Model
class Reading
belongs_to :customer
end
Invoice Model
class Invoice
belongs_to :customer
has_many :invoice_items
end
Invoice Items
class Invoiceitem
belongs_to :invoice
end
Creating a destroy action in my customers_controller deletes the customer however, it leaves a lot of orphaned records making it had for me to call the show action on the invoices controller due to nil values.
How can I be able to delete a customer and all the associated records in the models?
Upvotes: 0
Views: 20
Reputation: 5767
You can add :dependent => :destroy
to the has_many
The API Documentation section Deleting from associations contains this example.
For example:
class Author
has_many :posts, :dependent => :destroy
end
Author.find(1).destroy # => Will destroy all of the author's posts, too
Upvotes: 1