Usually, if you want to delete something through the has_many association, you put dependent: :destroy there:
class User has_many :partnerships, dependent: :destroy has_many :partners, through: :partnerships end
If you want to destroy partners , as well as partnerships, you must add this dependency to the Partnership model:
class Partnership belongs_to :partner, dependent: :destroy belongs_to :user end
When an object is destroyed, it causes destruction on each object in which the destroy function is provided. Thus, User causes destruction on each Partnership , and each call of Partnership destroys on each Partner .
"Why can't it be used with through " - well, the answer is "from the moment you delete it directly." I know this doesn't say much (for me either), but, on the other hand, for me adding dependencies to objects that are not directly related is a bad idea. Consider the above example: if the dependent - destroy will work on partners and destroy them - should it also destroy the connection model? Of course, yes, because in another case it will lead to data corruption, but you may lose some data that may be associated with the connection model, so in some cases, no, you do not want to destroy the join model. This means that the Rails team would have to add a new parameter, delete_join , to indicate whether you want to save this model or not. And this is just a bad design, since we already have a better approach - add dependencies to the connection model.
source share