如何使用 has_many 销毁记录,:dependent => :破坏

发布于 2024-09-30 08:25:36 字数 487 浏览 2 评论 0原文

我在几个插件的帮助下构建了一个 Rail 3 AuditLog,这些插件将数据存储在 AuditLog 表中,并具有以下用于标识的字段(feeded_id、feeded_type)。

所以就我而言,我有一个包含很多照片的相册。

class PhotoAlbum < ActiveRecord::Base
has_many :photos, :dependent => :destroy

当我删除相册(id = 2)时,这可以很好地删除所有关联的照片,但它不会从 AuditLog 中删除如下所示的项目:(feeded_id = 2,feeded_type = PhotoAlbum)

鉴于 AuditLog 表不没有“photo_album_id”列,并且不能,有没有办法设置依赖 >当删除相册时,使用 Rails Destory 删除 AuditLog 中的所有关联项目?

谢谢,我知道这个比大多数都复杂一点。感谢您阅读它!

I've built a Rail 3 AuditLog with the help of a few plugins, that store data in an AuditLog Table with the following fields for identification (feeded_id, feeded_type)

So in my case, I have a photoalbum that has_many photos.

class PhotoAlbum < ActiveRecord::Base
has_many :photos, :dependent => :destroy

when I delete a photoalbum (id=2) this works very well to delete all associated photos, but it doesn't delete items from the AuditLog that are like this: (feeded_id = 2, feeded_type = PhotoAlbum)

Given that the AuditLog table doesn't have a "photo_album_id" column, and can't, is there a way to setup a dependent > Destory with Rails to delete all associated items in teh AuditLog when a PhotoAlbum is deleted?

Thanks, I know this one's a little more complicated than most. Thanks for reading through it!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

童话里做英雄 2024-10-07 08:25:36

的组合

我认为您正在寻找的是belongs_to :feeded, :polymorphic => true

在您的审核日志类中,并且

has_many :logs, :as => :喂养,:依赖=> :destroy

在你的 PhotoAlbum 类中。

如果您没有一个类来表示您的审核日志,您应该能够将 belongs_to 添加到现有类中(也许在您的插件中?)。

我对 :as => 不是 100% 确定:feeded 选项,您必须正确命名该符号,我不确定 ActiveRecord 会期望什么,但是 belongs_to 关系将查找 feeded_id 和 feeded_type,因此当“父”对象是 PhotoAlbum 时它将正确加入 photo_album.id =audit_logs.feeded_id ANDaudit_logs.feeded_type = 'PhotoAlbum'。由于这不需要对数据库进行任何更改,因此所有现有代码应该继续工作。

您可以在此处阅读关联选项

I think what you are looking for is the combination of

belongs_to :feeded, :polymorphic => true

in your Audit log class and

has_many :logs, :as => :feeded, :dependent => :destroy

in your PhotoAlbum class.

If you do not have a class to represent your audit log, you should be able to add the belongs_to to the existing class (in your plugins perhaps?).

I'm not 100% sure about the :as => :feeded option, you will have to name that symbol correctly and I am not sure what ActiveRecord will expect, but the belongs_to relationship will look for feeded_id and feeded_type, so when the 'parent' object is a PhotoAlbum it will join correctly on photo_album.id = audit_logs.feeded_id AND audit_logs.feeded_type = 'PhotoAlbum'. Since this doesn't require any changes to your database, all your existing code should continue to work.

You can read up on the options for associations here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文