Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 739
Daniel Cukier Avatar asked Sep 10 '09 00:09

Daniel Cukier


2 Answers

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.

like image 168
cite Avatar answered Oct 27 '22 09:10

cite


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

has_many docs

like image 35
jdl Avatar answered Oct 27 '22 09:10

jdl