簡體   English   中英

Rails:每次上傳的主動存儲 has_many 關聯回調

[英]Rails: Active storage has_many association callback for each upload

我有我使用的這個模型有許多活動存儲關聯

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

或者您可以創建初始化程序來對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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM