Rails 3 habtm 仅删除关联
class Company
has_and_belongs_to_many :users
end
class User
has_and_belongs_to_many :companies
end
当我删除一家公司时,仅删除该公司用户关联的最佳(推荐)方法是什么? (我的意思不是实际用户,只是协会)
class Company
has_and_belongs_to_many :users
end
class User
has_and_belongs_to_many :companies
end
when i delete a company, what's the best (recommended) way to delete ONLY the associations of the users from that company? (i mean not the actual users, only the associations)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我更喜欢以下内容,因为它将模型逻辑保留在模型中。我不明白为什么 ActiveRecord 不这样做。无论如何,在两个连接模型中,我添加了以下回调。
因此,在您的示例中:
在围绕对集合关联进行级联删除的大量讨论中,许多人声明 HABTM 关联已死亡并建议使用 has_many :through 。我不同意。使用任何有意义的东西。如果关联没有内在属性,则使用 HABTM。
I prefer the following since it keeps model logic in the model. I don't understand why ActiveRecord doesn't just do it. Anyway, in both joined models, I add the following callback.
So in your example:
In a lot of discussions around doing a cascade delete on a collection association, many people declare the HABTM association dead and recommend has_many :through instead. I disagree. Use whatever makes sense. If the association has no intrinsic attributes, then use HABTM.
http://api.rubyonrails.org/classes/ActiveRecord /Associations/ClassMethods.html#method-i-has_and_belongs_to_many
collection.delete
就可以了。http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_and_belongs_to_many
collection.delete
will do the trick.如果您调用destroy而不是delete,关联将被自动删除。
If you call destroy instead of delete, associations will be deleted automatically.