0

我有一个用户类,其中has_many地址 - 和地址belongs_to用户。
我如何定义它,以便当一个地址被删除时它user.adresses也会被删除,反之亦然,如果我这样做user.addresses.delete(address),那么它不再出现在Addresses.all

4

2 回答 2

1

To destroy addresses when a user is deleted, you can declare it on the association.

class User < ActiveRecord::Base
  has_many :addresses, :dependent => :destroy #destroy addresses when user destroyed
end

You don't need to do anything for the other way around, since the foreign key is on the Address model.

于 2012-12-15T17:24:29.517 回答
0

您需要在 User 模型的 has_many 关系中传递 :dependent => :destroy

has_many :addresses, :dependent => :destroy

如果您这样做,则如果删除了用户,则与该用户关联的所有地址对象也将被删除。

于 2012-12-15T17:31:57.620 回答