Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何使用循环删除特定记录的所有关联记录?(不使用依赖项)_Ruby On Rails_Ruby On Rails 3_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 如何使用循环删除特定记录的所有关联记录?(不使用依赖项)

Ruby on rails 如何使用循环删除特定记录的所有关联记录?(不使用依赖项),ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 3,Ruby On Rails 4,如何使用循环删除特定记录的所有关联记录? 比如,当我删除一个特定的卖家时,他们的相关记录应该被删除。 当一个销售商被删除时,他们的产品、客户、销售商营销场所应该被删除。(不应该删除市场。) classseller

如何使用循环删除特定记录的所有关联记录? 比如,当我删除一个特定的卖家时,他们的相关记录应该被删除。 当一个销售商被删除时,他们的产品、客户、销售商营销场所应该被删除。(不应该删除市场。)

classseller
您的型号应为:-

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
 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
classseller
为什么不使用
卖方.产品.全部销毁
卖方.客户.全部销毁
@DeepakMahakale-Hi,要求通过循环销毁。所以我没有使用卖家。客户。全部销毁。好的。我想是他:D@DeepakMahakale,我有点搞不清楚如何摧毁卖方市场,正如他没有提到的那样,
有很多:卖方市场
那么我怎样才能同时摧毁
卖方市场
先生,你能指出我吗?@DeepakMahakale如果我是对的,那么应该是
有很多:卖方市场
有很多:通过::卖方市场
我说得对吗?我想你需要设置卖方市场协会
  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
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