【问题标题】:Do action after upload file with Active Storage使用 Active Storage 上传文件后执行操作
【发布时间】:2019-03-14 22:20:31
【问题描述】:

我的模型有一个has_many_attached :photos

第一次创建此模型时,它有 0 张照片。如果我运行photos.attached?,我会得到false

当用户上传一些文件到照片时,我需要做一些动作,但只是第一次。我尝试使用before_update :if photos.attached?。但我需要知道用户是否专门更新照片。

有没有办法知道用户是否正在尝试更新照片?或者有什么简单的方法可以做到这一点?

【问题讨论】:

  • 让我直截了当地说:只有在将照片第一次附加到您的model 时,您才需要知道如何执行操作?

标签: ruby-on-rails rails-activestorage


【解决方案1】:

您可以使用dirty? 方法

class Post < ApplicationRecord
  has_many_attached :photos

  before_update :do_whatever, if: -> { photos.dirty? } 

  def do_whatever
    # doing something
  end
end

你也可以试试before_update :do_whatever, if: -&gt; { photos_changed? }

【讨论】:

  • 我相信后面部分的正确语法是-&gt; {photos.changed?}
  • 我无法让它工作。我不断收到错误“#<:attached::many:0x00007fdaf09e0868> 的未定义方法 `dirty'”
【解决方案2】:

检查 Rails 模型中的回调(after_create、after_save 等)以及“on:​​create”和“update”选项。

【讨论】:

    【解决方案3】:

    Rails 没有添加向文件附件添加验证的功能。见Issue #31656

    试试这个方法:

    验证mime-types

    <%= f.file_field :photos, accept: "image/png,image/gif,image/jpeg', multiple: true %>
    

    您仍然需要添加模型验证。有关如何使用自定义验证器的信息,请参阅这篇文章 Validating the Content-Type of Active Storage Attachments

    要限制您的action 仅执行一次,您可以在您的model 中添加一个布尔字段,并在您的操作成功终止后将其设置为true。使用before_update 作为Antarr Byrd 建议在每张照片附加到您的模型后检查。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-11
      • 2015-10-13
      • 1970-01-01
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-03
      • 2020-04-05
      相关资源
      最近更新 更多