Search code examples
ruby-on-railsactiverecordcascadecascading-deletes

How can I make a cascade deletion in a one_to_many relationship in Rails ActiveRecord?


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

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

Solution

  • 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.

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