Ruby on rails rails是否清除模型的所有关系依赖项?
我有一个这样的模型:Ruby on rails rails是否清除模型的所有关系依赖项?,ruby-on-rails,ruby-on-rails-5,relationship,Ruby On Rails,Ruby On Rails 5,Relationship,我有一个这样的模型: class User < ActiveRecord::Base has_many :notifications, dependent: :delete_all has_many :foo, dependent: :delete_all has_many :bar, dependent: :delete_all end 为什么??因为如果以后,我的应用程序与新的“baz”有很多关系,这意味着我应该考虑添加我的用户.baz.delete\u all,我
class User < ActiveRecord::Base
has_many :notifications, dependent: :delete_all
has_many :foo, dependent: :delete_all
has_many :bar, dependent: :delete_all
end
为什么??因为如果以后,我的应用程序与新的“baz”有很多关系,这意味着我应该考虑添加
我的用户.baz.delete\u all
,我不会…你可以将此添加到你的用户模型中:
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\u有许多\u关联
您可以通过进行一些更改使此方法更通用。这将允许您销毁所有关联或特定关联,如有或属于:
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\u关联
,所有关联都将被删除。如果调用user.destroy\u关联(type::has\u many)
,则只会销毁has\u many关联。您可以将其添加到用户模型中:
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\u有许多\u关联
您可以通过进行一些更改使此方法更通用。这将允许您销毁所有关联或特定关联,如有或属于:
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\u关联
,所有关联都将被删除。如果调用user.destroy\u关联(type::has\u many)
,则只会销毁has\u many关联