首页 > 解决方案 > 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 来完成这项工作

标签: ruby-on-railsrails-activestorage

解决方案


你可以写这样的东西(它会第一次工作):

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

推荐阅读