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

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

How can I delete all relationship data for a store object in a connection table?

Can I use something like this:

store.categories.destroy or category.stores.destroy

Note. both models: has_and_belongs_to_many (and therefore without an identifier for each association entry - only store_id and category_id)

+6
source share
1 answer

In the has_and_belongs_to_many association has_and_belongs_to_many you can use delete_all or destroy_all .

In the has_many association, you must use delete_all because it deletes the entries following the strategy :dependent (defaults to nullifys foreign keys) instead of destroy_all , which destroys the related entries.

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

+6
source

Source: https://habr.com/ru/post/900935/


All Articles