ruby-on-rails - Rails:每次上传的活动存储has_many关联回调
问题描述
我有这个我正在使用的模型有很多活动的存储关联
class Cloud < ApplicationRecord
has_many_attached :images
has_many_attached :videos
validates :images, content_type: { in: ['image/png', 'image/jpg', 'image/jpeg', 'images/gif'] , message: 'should be of type png, jpg, jpeg and gif.'}
validates :videos, content_type: { in: ['video/mp4', 'video/x-flv', 'video/x-msvideo', 'video/x-ms-wmv', 'video/avi', 'video/quicktime'], message: 'should be of type mp4, x-flv, x-msvideo, x-ms-wmv, avi and quicktime(mov).' }
validates :videos, size: { greater_than: 1.kilobytes , message: 'size is invalid' }
validates :images, size: { greater_than: 1.kilobytes , message: 'size is invalid' }
end
现在我需要添加回调,每次添加任何视频时,如果没有内容类型,video/mp4
那么我将在 sidekiq 中使用 ffmpeg 将其转换我需要运行 worker 来完成这项工作
解决方案
你可以写这样的东西(它会第一次工作):
after_save :check_video_format
def check_video_format
if videos.attached?
videos.each do |video|
if video.persisted? && video.content_type != 'video/mp4'
# do your job here
end
end
end
end
或者您可以像这样为monkeypatch创建初始化程序ActiveStorage
:
require "active_support/core_ext/module/delegation"
class ActiveStorage::Attachment < ActiveRecord::Base
after_save :fix_video_format, if: -> { record_type == 'Cloud' && name == 'videos' }
def fix_video_format
if content_type != 'video/mp4'
# do your job here
end
end
end
推荐阅读
- java - 为什么我的计数器不计数并且我的 ArrayList 没有将新的整数值添加到数组中?
- java - 持有具有不同数量参数的函数映射
- python - “Post.user”必须是“用户”实例
- javascript - 如何使用 Mongoose 反映所需的数据
- arrays - 如何在scala中更新数组中的重复项
- c# - Get the user ID inside a custom middleware
- ios - Expo 构建在 CI 中失败,但在本地构建(babel-preset-expo 已被忽略,因为它包含无效配置)
- python - pyodbc - 使用 python 3 时游标不接受整数参数
- python - 在 Visual Studio Code 中使用 ImageFields 调试 Django 项目时出错
- amazon-web-services - 如何从 Azure Devops 管道连接 AWS EKS 集群 - 在 KubeConfig 内容中找不到集群的用户凭据