【问题标题】:how to hook for destroy of a model that belongs to another model?如何挂钩销毁属于另一个模型的模型?
【发布时间】:2013-01-03 17:56:21
【问题描述】:

我有一个用户模型有_many实验:

class User < ActiveRecord::Base

has_many :experiments, :dependent => :destroy

和实验模型:

class Experiment < ActiveRecord::Base

belongs_to :user
has_attached_file :thumbnail

我想在所有者用户被销毁后在实验模型上挂钩销毁时刻。 (前用户注销他的帐户)

我需要这样做以删除存储在亚马逊的 Experiment 模型的附件图像。喜欢experiment.thumbnail.destroy

推荐的方法是什么?

编辑

虽然我没有错误地销毁缩略图,但是文件仍然没有被删除!我仍然可以在亚马逊桶上看到它

class Experiment < ActiveRecord::Base
before_destroy :remove_attachment

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

我销毁实验后,调用了remove_attachment,但是errors.full_messages 是空的!所以没有错误,但是,文件仍然没有被删除

有什么想法吗??

【问题讨论】:

  • Paperclip 默认情况下会在删除相关记录(在您的情况下为实验)时删除文件。如果这没有发生,那么听起来您的 Amazon S3 配置存在问题(仅通过使用存储桶一词来猜测您正在使用 S3)配置。您是否检查了您的日志文件(production.log 或 development.log)以获取更多信息?
  • 但是我的设置在上传文件时工作正常,只是删除不起作用,我在日志文件中找不到任何东西..现在去哪里看?
  • 很难说。在您的问题中,您没有列出调用has_attached_file 的参数。你能补充一下吗?例如,有一个名为 :preserve_file 的配置选项默认为 false,在您的情况下应保持此状态。

标签: ruby-on-rails activerecord devise ruby-on-rails-3.2 paperclip


【解决方案1】:

我想在实验模型之后挂钩破坏时刻 owner 用户被销毁。

has_many :experiments, :dependent => :destroy

已经这样做了。

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

class Experiment < ActiveRecord::Base

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

【讨论】:

    【解决方案2】:

    我认为您正在寻找 callback 喜欢的:

    before_destroy :delete_attachment_image

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-03
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多