How can I cascade deletion in one_to_many relationships in Rails ActiveRecord?

I have a model in rails with one_to_many relation. When I delete a father, I want to remove all the children. How am I supposed to do this? I want to delete all orders and their items when I delete a user

My models:

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
+5
source share
2 answers

jdl the answer is correct - you need to add :dependent => :destroyto both relationships - that is, in your class User, add it to has_many :orders, and in your class Orderadd it to has_many :order_items.

You can also change the behavior of MySQL on foreign keys, perhaps by setting them to ON DELETE CASCADE.

+9

, , :dependent => :destroy has_many.

has_many docs

+5

All Articles