如何在Rails ActiveRecord中的one_to_many关系中进行级联删除?

时间:2022-10-04 15:37:40

I have a model in rails with one_to_many relationship. When I delete the father, I'd like to delete all childrens. How should I do it? I want to delete all orders and its items when I delete a user

我有一个带有one_to_many关系的rails模型。当我删除父亲时,我想删除所有孩子。我该怎么办?我想在删除用户时删除所有订单及其商品

My models are:

我的模特是:

class User < ActiveRecord::Base
  has_many :orders, :foreign_key => "id_user"
end

class Order < ActiveRecord::Base
  has_many :order_items, :foreign_key => "id_pedido"
  belongs_to :user, :foreign_key => "id_usuer"
end

class OrderItem < ActiveRecord::Base
  belongs_to :order, :foreign_key => "id_pedido"
end

2 个解决方案

#1


9  

jdl's answer is correct - you need to add :dependent => :destroy to both relationships - i.e. in your User class, add it to has_many :orders, and in your Order class, add it to has_many :order_items.

jdl的答案是正确的 - 您需要在两个关系中添加:dependent =>:destroy - 即在您的User类中,将其添加到has_many:orders,在Order类中,将其添加到has_many:order_items。

You might also want to change the MySQL behaviour wrt foreign keys, perhaps setting them to ON DELETE CASCADE.

您可能还想更改外键的MySQL行为,可能将它们设置为ON DELETE CASCADE。

#2


5  

What you're looking for is the :dependent => :destroy option on has_many.

你要找的是has_many上的:dependent =>:destroy选项。

has_many docs

has_many docs

#1


9  

jdl's answer is correct - you need to add :dependent => :destroy to both relationships - i.e. in your User class, add it to has_many :orders, and in your Order class, add it to has_many :order_items.

jdl的答案是正确的 - 您需要在两个关系中添加:dependent =>:destroy - 即在您的User类中,将其添加到has_many:orders,在Order类中,将其添加到has_many:order_items。

You might also want to change the MySQL behaviour wrt foreign keys, perhaps setting them to ON DELETE CASCADE.

您可能还想更改外键的MySQL行为,可能将它们设置为ON DELETE CASCADE。

#2


5  

What you're looking for is the :dependent => :destroy option on has_many.

你要找的是has_many上的:dependent =>:destroy选项。

has_many docs

has_many docs