加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何挂钩以破坏属于另一个模型的模型?

发布时间:2020-12-17 02:33:26 所属栏目:百科 来源:网络整理
导读:我有一个用户模型,其中有很多实验: class User ActiveRecord::Basehas_many :experiments,:dependent = :destroy 和实验模型: class Experiment ActiveRecord::Basebelongs_to :userhas_attached_file :thumbnail 我想在所有者用户被销毁后在实验模型中勾
我有一个用户模型,其中有很多实验:

class User < ActiveRecord::Base

has_many :experiments,:dependent => :destroy

和实验模型:

class Experiment < ActiveRecord::Base

belongs_to :user
has_attached_file :thumbnail

我想在所有者用户被销毁后在实验模型中勾解破坏时刻. (前用户取消他的帐户)

我需要删除实验模型的附件图像,该图像存储在亚马逊中.喜欢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为空!所以没有错误,仍然没有删除文件

任何的想法 ??

解决方法

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

has_many :experiments,:dependent => :destroy

已经那样做了.

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

class Experiment < ActiveRecord::Base

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读