使用 Active Storage 上传文件后执行操作
Do action after upload file with Active Storage
我的模型有 has_many_attached :photos
.
这个模型是第一次创建,有0张照片。如果我 运行 photos.attached?
我得到 false
.
当用户上传一些文件到照片时,我需要做一些操作,但只是第一次。我尝试使用 before_update :if photos.attached?
。但我需要知道用户是否专门更新照片。
有没有办法知道用户是否正在尝试更新照片?或者有没有简单的方法可以做到这一点?
检查 rails 模型和选项 "on: :create" 和 "update" 中的回调(after_create、after_save 等)。
有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: -> { photos_changed? }
Rails has not added the ability to add validations to file attachments. See Issue #31656
试试这个方法:
验证mime-types
:
<%= f.file_field :photos, accept: "image/png,image/gif,image/jpeg', multiple: true %>
您仍然需要添加模型验证。请参阅此 post 验证活动存储附件的内容类型
关于如何使用自定义验证器。
要限制您的 action
只执行一次,您可以在您的 model
中添加一个布尔字段,并在您的操作成功终止后将其设置为 true
。使用 before_update
作为 Antarr Byrd 建议在每张照片附加到您的模型后进行检查。
我的模型有 has_many_attached :photos
.
这个模型是第一次创建,有0张照片。如果我 运行 photos.attached?
我得到 false
.
当用户上传一些文件到照片时,我需要做一些操作,但只是第一次。我尝试使用 before_update :if photos.attached?
。但我需要知道用户是否专门更新照片。
有没有办法知道用户是否正在尝试更新照片?或者有没有简单的方法可以做到这一点?
检查 rails 模型和选项 "on: :create" 和 "update" 中的回调(after_create、after_save 等)。
有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: -> { photos_changed? }
Rails has not added the ability to add validations to file attachments. See Issue #31656
试试这个方法:
验证mime-types
:
<%= f.file_field :photos, accept: "image/png,image/gif,image/jpeg', multiple: true %>
您仍然需要添加模型验证。请参阅此 post 验证活动存储附件的内容类型 关于如何使用自定义验证器。
要限制您的 action
只执行一次,您可以在您的 model
中添加一个布尔字段,并在您的操作成功终止后将其设置为 true
。使用 before_update
作为 Antarr Byrd 建议在每张照片附加到您的模型后进行检查。