我有一個項目有很多項目;它是:dependent => :destroy
。 我在調用回調(特別是Item的after_destroy
)時試圖告訴導軌,只有當Item被「單獨」銷燬時才運行,但所有項目都不被銷燬。 當整個項目被銷燬時,我實際上並不需要(項目的)這個after_destroy
方法來運行。遇到問題:依賴=>:銷燬和實例變量
我不想做:dependent => :delete
,因爲Item中有許多其他關聯連接到它(與:dependent => :destroy
)。
它爲我的作品只與類變量,但我希望它曾與一個實例變量工作:
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
我能想到的是另一種選擇刪除:dependent => :destroy
和手動處理破壞的項目after_destroy
方法中的項目,但它似乎也太難看了,特別是因爲Project
有許多項目類型:dependent => :destroy
必須轉移到該方法。
任何想法,將不勝感激
一個類變量肯定是不正確的,sinc e適用於*所有*項目。你真的只想要一個項目實例... – DGM 2012-01-01 14:48:41
DGM - 我同意。這個類變量絕對是一個不好的選擇。 – user198026 2012-01-01 17:31:11