alavni shubham
alavni shubham

Reputation: 99

How to delete all associated records of Specific record using loop? (not Using dependent)

How to delete all associated records of Specific record using a loop? like When I will delete one Specific Seller at that time their related record should be deleted. eg. when One Seller is deleted that time their Products, Customer, SellerMarketplace should be deleted.(Not Marketplace should be deleted.)

class Seller < ActiveRecord::Base
    has_many :products
    has_many :customers
    has_many :seller_marketplaces
    has_many :marketplaces through: :seller_marketplaces
end

Upvotes: 1

Views: 441

Answers (2)

sank
sank

Reputation: 1014

You can use after_destroy callback

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

Upvotes: 0

Anand
Anand

Reputation: 6531

Your model should be : -

class Seller < ActiveRecord::Base
    has_many :products
    has_many :customers
    has_many :seller_marketplaces
    has_many :marketplaces through: :seller_marketplaces
end

Lets say you get one seller

  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

Upvotes: 2

Related Questions