Rails 中关联记录未删除

发布于 2024-10-29 16:26:33 字数 668 浏览 2 评论 0原文

我正在尝试将一组上传的图片与帖子关联起来。在我的控制器中,我使用以下代码:

image_uploads = params[:image_uploads]
iu = ImageUpload.find(image_uploads)
@post.image_uploads = iu

虽然这确实可以从 @post.image_uploads 访问上传的图像,但我认为它不会将这些图像与帖子关联起来,因为当帖子被删除时,上传的图像不会被删除——即使我使用了 :dependent=>:destroy 来表示它们的关系。

> Post.first.delete
=>[]
> ImageUpload.all
=> [#<ImageUpload id: 3 ...>] 

这就是模型:

class Post < ActiveRecord::Base
 has_many :image_uploads, :dependent => :destroy

end

class ImageUploads < ActiveRecord::Base
 belongs_to :post

end

我可以做什么来确保级联删除有效?

I am trying to associate a set of uploaded pictures with a post. In my controller I am using the following code:

image_uploads = params[:image_uploads]
iu = ImageUpload.find(image_uploads)
@post.image_uploads = iu

While this does make the uploaded images accessible from @post.image_uploads, I think it doesn't associate these images with the post because when the post is deleted, the image uploads are not deleted -- even though I have used :dependent=>:destroy for their relationships.

> Post.first.delete
=>[]
> ImageUpload.all
=> [#<ImageUpload id: 3 ...>] 

And this is the model:

class Post < ActiveRecord::Base
 has_many :image_uploads, :dependent => :destroy

end

class ImageUploads < ActiveRecord::Base
 belongs_to :post

end

What can I do to make sure that cascading deletes work?

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

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

发布评论

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

评论(2

执笔绘流年 2024-11-05 16:26:33

尝试改为:

Post.first.destroy

destroy 调用定义的回调,而 delete 直接使用 SQL 删除记录,而不创建 AR 对象。

Try instead:

Post.first.destroy

destroy invokes the callbacks defined, whereas delete deletes the record directly using SQL without creating an AR object.

生生漫 2024-11-05 16:26:33

你所做的对我来说似乎是正确的。您有一个帖子,其中的图像上传取决于该帖子,您应该在删除帖子时删除它们。我可能是错的,但我什么也没看到。

但是,我看到一些可能会导致严重问题的东西,它也可能是您问题的根源(它是许多问题的根源)。

您有一个以 S 结尾的模型。这不是一个好主意。帮自己一个忙,请更改为 ImageUpload :)

What you do seems correct to me. You have a post with image uploads dependent on the post and you should get them deleted when a post is deleted. I could be wrong but i do not see anything.

However, i see something that could cause heavy problems and it could also be the source of your problem(it's a source of many).

You have a model that ends with an S. Not a good idea. Do yourself a favor and change to ImageUpload please :)

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