我使用的这个模型具有许多活动存储关联
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来完成这项工作
答案 0 :(得分:0)
您可以编写类似的内容(它将在第一次使用):
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
或者您可以创建初始化器来像这样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