Rails 中关联记录未删除
我正在尝试将一组上传的图片与帖子关联起来。在我的控制器中,我使用以下代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试改为:
destroy
调用定义的回调,而delete
直接使用 SQL 删除记录,而不创建 AR 对象。Try instead:
destroy
invokes the callbacks defined, whereasdelete
deletes the record directly using SQL without creating an AR object.你所做的对我来说似乎是正确的。您有一个帖子,其中的图像上传取决于该帖子,您应该在删除帖子时删除它们。我可能是错的,但我什么也没看到。
但是,我看到一些可能会导致严重问题的东西,它也可能是您问题的根源(它是许多问题的根源)。
您有一个以 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 :)