简体   繁体   中英

Rails dependent destroy all

How do I generate a delete cascade in Rails?

I have these models:

class UploadFile < ActiveRecord::Base
   has_many :purchases, dependent: :delete_all
end

class Purchase < ActiveRecord::Base
    has_many :purchasers,   dependent: :delete_all
    has_many :items,        dependent: :delete_all
    has_many :merchants,    dependent: :delete_all

    has_one :upload_file
end

class Item < ActiveRecord::Base
end 

class Item < ActiveRecord::Base
end 

class Item < ActiveRecord::Base
end

When I delete upload_file only the Purchase's data will be destroyed. The rest still exist in the DB.

What I am doing wrong?

You should be using destroy_all here not delete_all .

From the api dock :

destroy_all(conditions = nil) public

Destroys the records matching conditions by instantiating each record and calling its destroy method. Each object's callbacks are executed (including :dependent association options and before_destroy/after_destroy Observer methods).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM