I have a project with many items; and it's :dependent => :destroy
.
I'm trying to tell rails when calling callbacks (specifically the after_destroy
of Item), to run ONLY if the Item is destroyed "alone", but all of the project is NOT being destroyed.
When the whole project is being destroyed, I actually don't need this after_destroy
method (of Item) to run at all.
I don't want to do :dependent => :delete
since the Item has many other associations connected to it (with :dependent => :destroy
).
It works for me only with class variable, but I wish it would had worked with an instance variable:
class Project < ActiveRecord::Base
has_many :items, :dependent => :destroy
before_destroy :destroying_the_project
def destroying_the_project
# this is a class variable, but I wish I could had @destroying_me
# instead of @@destroying_me.
@@destroying_me = true
end
def destroying_the_project?
@@destroying_me
end
end
class Item < ActiveRecord::Base
belongs_to :project
after_destroy :update_related_statuses
def update_related_statuses
# I with I could had return if project.destroying_the_project?
# but since the callback gets the project from the DB, it's another instance,
# so the instance variable is not relevant here
return if Project::destroying_the_project?
# do a lot of stuff which is IRRELEVANT if the project is being destroyed.
# this doesn't work well since if we destroy the project,
# we may have already destroyed the suites and the entity
suite.delay.suite_update_status
entity.delay.update_last_run
end
end
The other option I can think of is remove the :dependent => :destroy
and manually handle the destroy of the items inside the Project after_destroy
method, but it seems too ugly as well, especially since Project
has many item types with :dependent => :destroy
that would have to shift to that method.
Any ideas would be appreciated