Rails:每次上传的活动存储has_many关联回调

问题描述 投票:0回答:1

我使用的这个模型具有许多活动存储关联

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来完成此工作

ruby-on-rails rails-activestorage
1个回答
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

或者您可以创建初始化程序来像这样对MonkeyCatch 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
© www.soinside.com 2019 - 2024. All rights reserved.