views:

337

answers:

2

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
A: 

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

has_many docs

jdl
I tried it, but I get this: Cannot delete or update a parent row: a foreign key constraint fails (`detam2`.`order_items`, CONSTRAINT `FKE3418DF1BA998374` FOREIGN KEY (`id_order`) REFERENCES `orders` (`id`)): DELETE FROM `orders` WHERE (`id` IN (31)) ActiveRecord::StatementInvalid: Mysql::Error: Cannot delete or update a parent row: a foreign key constraint fails (`detam2`.`order_items`, CONSTRAINT `FKE3418DF1BA998374` FOREIGN KEY (`id_order`) REFERENCES `pedidos` (`id`)): DELETE FROM `orders` WHERE (`id` IN (31))
Daniel Cukier
You are both right @jdl and @cite. What I was doing wrong was that I was calling the delete method besides the destroy method. Now everything works fine
Daniel Cukier
+2  A: 

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.

cite
You are both right @jdl and @cite. What I was doing wrong was that I was calling the delete method besides the destroy method. Now everything works fine
Daniel Cukier