how to hook for destroy of a model that belongs to another model?

巧了我就是萌 提交于 2019-12-23 12:51:48

问题


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 ??


回答1:


I want to hook for destroy moment at the Experiment model after the owner User get destroyed.

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



回答2:


I think you are looking for a callback like:

before_destroy :delete_attachment_image



来源:https://stackoverflow.com/questions/14144454/how-to-hook-for-destroy-of-a-model-that-belongs-to-another-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!