如何使用循环删除特定记录的所有关联记录? (不使用依赖)
How to delete all associated records of Specific record using loop? (not Using dependent)
如何使用循环删除特定记录的所有关联记录?
比如当我删除一个特定的卖家时,他们的相关记录应该被删除。
例如。当一个卖家被删除时,他们的产品、客户、SellerMarketplace 应该被删除。(而不是 Marketplace 应该被删除。)
class Seller < ActiveRecord::Base
has_many :products
has_many :customers
has_many :seller_marketplaces
has_many :marketplaces through: :seller_marketplaces
end
您的模型应该是:-
class Seller < ActiveRecord::Base
has_many :products
has_many :customers
has_many :seller_marketplaces
has_many :marketplaces through: :seller_marketplaces
end
假设您有一个卖家
def destroy
seller = Seller.find(params[:id])
products = seller.products
customers = seller.customers
seller_marketplaces = seller.seller_marketplaces
if seller.destroy
#delete products
products.each do |product|
product.destroy
end
#delete customers
customers.each do |customer|
customer.destroy
end
#delete seller_marketplaces
seller_marketplaces.each do |mp|
mp.destroy
end
end
end
您可以使用after_destroy回调
class Seller < ActiveRecord::Base
has_many :products
has_many :customers
has_many :seller_marketplaces
has_many :marketplaces through: :seller_marketplaces
after_destroy :destroy_related_records
def destroy_related_records
#delete products
products.each do |product|
product.destroy
end
#delete customers
customers.each do |customer|
customer.destroy
end
#delete seller_marketplaces
seller_marketplaces.each do |seller_marketplace|
seller_marketplace.destroy
end
end
end
如何使用循环删除特定记录的所有关联记录? 比如当我删除一个特定的卖家时,他们的相关记录应该被删除。 例如。当一个卖家被删除时,他们的产品、客户、SellerMarketplace 应该被删除。(而不是 Marketplace 应该被删除。)
class Seller < ActiveRecord::Base
has_many :products
has_many :customers
has_many :seller_marketplaces
has_many :marketplaces through: :seller_marketplaces
end
您的模型应该是:-
class Seller < ActiveRecord::Base
has_many :products
has_many :customers
has_many :seller_marketplaces
has_many :marketplaces through: :seller_marketplaces
end
假设您有一个卖家
def destroy
seller = Seller.find(params[:id])
products = seller.products
customers = seller.customers
seller_marketplaces = seller.seller_marketplaces
if seller.destroy
#delete products
products.each do |product|
product.destroy
end
#delete customers
customers.each do |customer|
customer.destroy
end
#delete seller_marketplaces
seller_marketplaces.each do |mp|
mp.destroy
end
end
end
您可以使用after_destroy回调
class Seller < ActiveRecord::Base
has_many :products
has_many :customers
has_many :seller_marketplaces
has_many :marketplaces through: :seller_marketplaces
after_destroy :destroy_related_records
def destroy_related_records
#delete products
products.each do |product|
product.destroy
end
#delete customers
customers.each do |customer|
customer.destroy
end
#delete seller_marketplaces
seller_marketplaces.each do |seller_marketplace|
seller_marketplace.destroy
end
end
end