Imagine a scenario where I have a model that has categories. The model belongs_to a category, and the category has_many models. The has_many relationship has a dependent: :destroy condition.
However I have a default category (essentially "not specified") that I would like to use as a fall back. So imagine category 1 is deleted - what should happen is that all the records of the model that were associated with category 1 should automatically be assigned to "not specified".
Any hints into the right direction appreciated.
CodePudding user response:
What you saying is that you don't want to destroy dependent models:
class Category < ApplicationRecord
has_many :models #,dependent: :destroy
before_destroy do
models.update_all(category_id: Category.first.id) # fallback to default category
end
end