gpt4 book ai didi

ruby-on-rails - 遇到 :dependent => :destroy and Instance variables 问题

转载 作者:太空宇宙 更新时间:2023-11-03 16:35:16 25 4
gpt4 key购买 nike

我有一个包含很多项的项目;它是 :dependent => :destroy。我试图在调用回调(特别是 Item 的 after_destroy)时告诉 rails,仅当 Item 被“单独”销毁时才运行,但所有项目都没有被销毁。当整个项目被销毁时,我实际上根本不需要这个after_destroy方法(Item)来运行。

我不想执行 :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 的项类型,它们必须转移到那个方法。

任何想法将不胜感激

最佳答案

我希望这不是最好的解决方案,但至少它可以工作并且不会通过类变量引入任何全局状态:

class Project < ActiveRecord::Base
has_many :items
before_destroy :destroying_the_project

def destroying_the_project
Rails.logger.info 'Project#destroying_the_project'
items.each &:destroy_without_statuses_update
end
end

class Item < ActiveRecord::Base
belongs_to :project
after_destroy :update_related_statuses,
:unless => :destroy_without_statuses_update?

def update_related_statuses
Rails.logger.info 'Item#update_related_statuses'
end

def destroy_without_statuses_update
@destroy_without_statuses_update = true
destroy
end

def destroy_without_statuses_update?
!!@destroy_without_statuses_update
end
end

关于ruby-on-rails - 遇到 :dependent => :destroy and Instance variables 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8693408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com