Reputation: 5896
Is there a way to set a sort of dependent:destroy
that will null an id but not destroy the record? For instance, I have a Order model that contains information about a patron's orders. I also have a Patron model that contains info about the patron. When I destroy a patron, I'd like all the ids for that patron (patron_id) in Order to be null now, so as to avoid weird mixups with new patrons, should that id be reused. However, I still want to keep the Order record for analysis of what was ordered the most, etc. Is there a relationship that defines this?
Example:
Order
Patron
A patron has_many: orders
. An order belongs_to: patron
Lets say I have patrons [{1,'Bob'},{2,'Sally'}]
And orders [{1,2,'Cake'},{2,2,'Screwdriver'},{3,1,'Ham'}]
Then I destroy sally, making patrons [{1,'Bob'}].
I'd want orders to be [{1,null,'Cake'},{2,null,'Screwdriver'},{3,1,'Ham'}]
How would I do this?
Upvotes: 1
Views: 573
Reputation: 5998
You need to use option nullify
has_many :orders, dependent: :nullify
see more details in chapter 4.2.2.4 :dependent
Upvotes: 3