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