Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destroy all association data between two models? (Rails beginner)

I have two models: store and category with a joining table called categories.stores.

How could I delete all relationship data for a store object in the joining table?

Could I use something like one of these:

store.categories.destroy or category.stores.destroy

Note: both models are has_and_belongs_to_many (and thus have no identifier for each association record -- only store_id and category_id)

like image 524
Hopstream Avatar asked Nov 07 '11 13:11

Hopstream


1 Answers

In a has_and_belongs_to_many association you can either use delete_all or destroy_all.

In a has_many association you should consider using delete_all because it deletes records following the :dependent strategy (it nullifys foreign keys by default) instead of destroy_all which destroys associated records.

More details at http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Delete+or+destroy%3F

like image 51
davidb Avatar answered Nov 04 '22 21:11

davidb