tkhobbes
tkhobbes

Reputation: 682

How can I revert to a fallback in a Rails has_many dependent: :destroy scenario?

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.

Upvotes: 1

Views: 81

Answers (1)

Alex
Alex

Reputation: 29751

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

Update Let's double check.

class Category < ApplicationRecord
  has_many :posts
  before_destroy do
    posts.update_all(category_id: Category.find_by(name: "DEFAULT").id)
  end
end

class Post < ApplicationRecord
  belongs_to :category
end
Category.create(name: "DEFAULT")
Category.create(name: "ONE", posts: [Post.new, Post.new])
Category.create(name: "TWO", posts: [Post.new, Post.new])

>> Post.joins(:category).group("categories.name").count
=> {"ONE"=>2, "TWO"=>2}

>> Category.find_by(name: "TWO").destroy
>> Post.joins(:category).group("categories.name").count
=> {"ONE"=>2, "DEFAULT"=>2}   # posts from category TWO moved to DEFAULT

>> Category.find_by(name: "ONE").destroy
>> Post.joins(:category).group("categories.name").count
=> {"DEFAULT"=>4}             # posts from category ONE moved to DEFAULT

Upvotes: 0

Related Questions