[英]Associated record is not deleted in Rails
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.image_uploads
访问上载的图像,但我认为它不会将这些图像与该帖子相关联,因为删除该帖子时,不会删除这些图像的上载-即使我使用了:dependent=>:destroy
为他们的关系。
> 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? 我该怎么做才能确保级联删除工作?
Try instead: 请尝试:
Post.first.destroy
destroy
invokes the callbacks defined, whereas delete
deletes the record directly using SQL without creating an AR object. destroy
调用定义的回调,而delete
使用SQL直接删除记录,而无需创建AR对象。
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. 您有一个以S结尾的模型。这不是一个好主意。 Do yourself a favor and change to ImageUpload please :)
帮自己一个忙,请更改为ImageUpload :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.