how to hook for destroy of a model that belongs to

2019-06-27 02: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