Should nested attributes be automatically deleted when I delete the parent record?
- by brad
I'm playing around with nested forms in attributes and have a model Invoice that has_many invoice_phone_numbers. I have the following line in my invoice.rb model file
accepts_nested_attributes_for :invoice_phone_numbers, :allow_destroy => true, :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
This does what it should and I can delete invoice_phone_numbers from the form by selecting their 'delete' checkbox. But when I delete an Invoice, I have noticed that the nested invoice_phone_numbers are not also deleted. This causes problems as rails seems to reuse id numbers in the Invoice model (Should it? Does this depend on the database? I'm using SQLite3) so phone numbers from previous invoices turn up in new invoices after they have been created. Anyway, my question is should the nested attributes be deleted when I delete the parent attribute? Is there a way to make this happen automatically as part of the nesting process or do I need to deal with this in my invoice model? If so, what is the best way to do this? I would try to go about this with a before_destroy callback but want to know if this is the best way to do this.
Anyway, thanks.