Ruby on rails 如何在destroy上跳过依赖模型中的回调
我有供应商和职位。当提供者被销毁时,我需要销毁任何位置。但是,我的Ruby on rails 如何在destroy上跳过依赖模型中的回调,ruby-on-rails,Ruby On Rails,我有供应商和职位。当提供者被销毁时,我需要销毁任何位置。但是,我的check\u primary方法位于位置。当我尝试销毁提供程序时,rb正在崩溃 provider.rb has_many :positions, dependent: :destroy after_destroy :check_primary def check_primary unless provider.primary_position # this shouldn't run when destr
check\u primary
方法位于位置。当我尝试销毁提供程序时,rb
正在崩溃
provider.rb
has_many :positions, dependent: :destroy
after_destroy :check_primary
def check_primary
unless provider.primary_position # this shouldn't run when destroying a provider
if provider.positions.present?
provider.positions.first.update_column(:primary, true) # crash here
end
end
end
位置.rb
has_many :positions, dependent: :destroy
after_destroy :check_primary
def check_primary
unless provider.primary_position # this shouldn't run when destroying a provider
if provider.positions.present?
provider.positions.first.update_column(:primary, true) # crash here
end
end
end
提供程序销毁时出错:无法更新已销毁的记录
我的问题
我想在provider.rb
中放置一个skip_回调,每当调用provider.destroy
方法时,它都会跳过location.rb中的check_primary
我如何才能做到这一点?
使用pry从内分析父对象时:检查\u primary
我看到:
>> provider.destroyed?
=> false
>> provider.frozen?
=> false
>> provider.marked_for_destruction?
=> false
更新
我现在想不出来。。。所以这里有一个非常糟糕的解决方法:
def check_primary
unless provider.primary_position
begin
provider.positions.first.update_column(:primary, true)
rescue
nil
end
end
end
尝试在销毁上下文中跳过它。在position.rb中:
skip_callback :check_primary, on: destroy
编辑以解决我的误解。我对我最初的离题答案更有信心,但我相信你可以通过一个条件,如下所示:
skip_callback :check_primary, if: -> { #conditions }
我相信Rails对此有一个回调:after\u remove
,在本例中,它的用法类似于(在Provider.rb中)——
然后将check_primary
移动到Provider模型中,并将其修改为从该类而不是Position类中执行操作。对不起,一些背景:我在销毁职位时调用此方法,以确保在用户删除其主职位时分配主职位。啊--我现在看到销毁后的操作。我需要更仔细地阅读。请留下你的答案,因为它可能会帮助别人。谢谢。所以现在我在销毁后尝试:检查\u primary,除非:->{conditions}
,但是我真的不知道在provider.destromed之后应该为条件放什么?计算结果为false。我明白了。在没有更好的理解的情况下很难帮助解决这种情况。销毁
之前,能否分配不同的主?这样,您仍然可以访问该对象。