私は多くのアイテムを持つプロジェクトを持っています。それは:dependent => :destroy
です。 コールバック(特にItemのafter_destroy
)を呼び出すときに、アイテムが "単独"で破棄されたが、すべてのプロジェクトが破棄されていない場合にのみ実行するように、レールに伝えようとしています。 プロジェクト全体が破壊されているとき、実際には(アイテムの)after_destroy
メソッドを実行する必要はありません。問題があります:依存=>:破棄とインスタンス変数
:dependent => :delete
には、多くの他の関連付けが接続されています(: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
を削除し、手動での破壊を扱うですProject
には:dependent => :destroy
のアイテムタイプがあり、そのメソッドに移動しなければならないため、これはあまりにも醜いと思われます。
すべてのアイデアは、あなたがプロジェクト全体を削除するときのコールバックを使用する必要がない場合、あなたはDELETE_ALL使う代わりに破壊する可能性が
クラス変数は確かに正しくない、sincすべての*プロジェクトに適用されます。あなたは本当に1つのプロジェクトインスタンスだけを望んでいます... – DGM
DGM - 私は同意します。このクラス変数は間違った選択肢です。 – user198026