rails清除模型的所有关系依赖关系?

问题描述 投票:0回答:1

我有一个模型:

class User < ActiveRecord::Base
   has_many :notifications, dependent: :delete_all
   has_many :foo, dependent: :delete_all
   has_many :bar, dependent: :delete_all
end

我如何启动dependent: :delete_all就像我调用my_user.destroy但没有销毁或删除我的用户?

如果我只想重置所有链接而不丢失我的用户?

我需要通用流程,而不是手动:

my_user.notifications.delete_all
my_user.foo.delete_all
my_user.bar.delete_all

为什么?因为如果以后,我的应用程序进化了一个新的“baz”has_many关系,这意味着我应该考虑添加my_user.baz.delete_all,我不会......

ruby-on-rails ruby-on-rails-5 relationship
1个回答
2
投票

您可以将其添加到您的用户模型:

def destroy_has_many_associations
  has_many_associations = self.reflect_on_all_associations(:has_many)

  has_many_associations.each do |association|
    send(association.name).destroy_all
  end
end

当您需要重置用户时,可以调用user.destroy_has_many_associations

您可以通过进行一些更改来使此方法更通用。这将允许您销毁所有关联或特定的关联,如has_many或belongs_to:

def destroy_associations(type: nil)
  reflections = self.reflect_on_all_associations(type)

  reflections.each do |reflection|
    association = send(reflection.name)
    reflection.macro == :has_many ? association.destroy_all : association.destroy
  end
end

如果您致电user.destroy_associations,将删除所有关联。如果你打电话给user.destroy_associations(type: :has_many),只会销毁has_many关联。

© www.soinside.com 2019 - 2024. All rights reserved.