Question

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
Was it helpful?

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.

OTHER TIPS

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

has_many docs

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top