本文介绍了如何挂钩的破坏属于另一个模式的典范?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户模型的has_many实验:

 类用户的LT;的ActiveRecord :: Base的

的has_many:实验:依赖=> :破坏
 

和实验模型:

 类实验<的ActiveRecord :: Base的

belongs_to的:用户
has_attached_file:缩图
 

我要挂钩的毁灭瞬间的实验模型中的所有者用户被摧毁后。 (例如用户取消他的帐户)

我必须这样做删除的实验模型,它存储在亚马逊的附件图像。如 experiment.thumbnail.destroy

什么是推荐的方式做到这一点?

修改

虽然我已经毁了缩略图没有错误,但是,该文件还没有删除!我仍然可以看到它在亚马逊斗

 类实验<的ActiveRecord :: Base的
before_destroy:remove_attachment

高清remove_attachment
    self.thumbnail.destroy
    把self.errors.full_messages.join(\ N)
    真正
结束
 

在我破坏实验,remove_attachment叫,但errors.full_messages是空的!所以没有错误,但仍然在文件没有被删除在降压

任何想法??

解决方案

 的has_many:实验:依赖=> :破坏
 

已经做到这一点。

要删除附件,我建议使用一个回调

 类实验<的ActiveRecord :: Base的

    before_destroy {|试验| experiment.thumbnail.destroy}
结束
 

I have a User model which has_many experiments:

class User < ActiveRecord::Base

has_many :experiments, :dependent => :destroy

and Experiment model:

class Experiment < ActiveRecord::Base

belongs_to :user
has_attached_file :thumbnail

I want to hook for destroy moment at the Experiment model after the owner User get destroyed. (ex user cancel his account)

I need to do so to delete the attachment image of the Experiment model, which is stored at amazon. like experiment.thumbnail.destroy

What is the recommended way to accomplish this?

EDIT

Although I have destroyed the thumbnail with no errors, but, the file is still not removed! i can still see it at amazon bucket

class Experiment < ActiveRecord::Base
before_destroy :remove_attachment

def remove_attachment
    self.thumbnail.destroy
    puts self.errors.full_messages.join("\n")
    true
end

After I destroy the experiment, remove_attachment is called, but errors.full_messages are empty! so there is no errors, but, still the file is not deleted at the buck

Any idea ??

解决方案
has_many :experiments, :dependent => :destroy

already does that.

To remove the attachment, I recommend using a callback

class Experiment < ActiveRecord::Base

    before_destroy { |experiment| experiment.thumbnail.destroy }
end

这篇关于如何挂钩的破坏属于另一个模式的典范?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 13:20
查看更多