ruby 在Rails中,如何向CarrierWave上传程序传递附加变量?

xmjla07d  于 2022-11-04  发布在  Ruby
关注(0)|答案(2)|浏览(109)

我看到这个问题在过去几年里被问了几次(例如Upload path based on a record value for Carrier wave DirectPassing a parameter to the uploader / accessing a model's attribute from within the uploader / letting the user pick the thumbnail size),但我确信我一定是把这个问题过于复杂了,因为它看起来像是一个非常简单的问题...
我有一个非常简单的Video模型,它安装了一个上传程序:

class Video < ApplicationRecord
  mount_uploader :file, VideoUploader
end

在控制器中,我允许两个参数:

def video_params
      params.require(:video).permit(:title, :file)
    end

在实际的VideoUploader中,我似乎可以使用类内置函数访问从:file列派生的许多变量(例如original_filename),我可以使用ffmpeg参数处理文件。但是,我希望参数是基于:title字符串的条件,并且我不知道如何限定它的范围或访问它。要确保这些方法可以访问该变量,最简单的方法是什么?
编辑:这里是上传器代码:

class VideoUploader < CarrierWave::Uploader::Base

  require 'streamio-ffmpeg'
  include CarrierWave::Video
  case @title # not working
  when "tblend_glitch"
    process encode_video: [:mp4,
      resolution: "1280x960",
      custom: %w(-to 5 -vf scale=-2:720,tblend=all_mode=difference,tblend=all_mode=difference,tblend=all_mode=difference,spp=4:10,tblend=all_mode=average,tblend=all_mode=difference,tblend=all_mode=difference,tblend=all_mode=difference,spp=4:10,tblend=all_mode=average,tblend=all_mode=difference,tblend=all_mode=difference,tblend=all_mode=difference,spp=4:10,tblend=all_mode=average,tblend=all_mode=difference,tblend=all_mode=difference,tblend=all_mode=difference)]
...
  end
  def full_filename(for_file)
    super.chomp(File.extname(super)) + '.mp4'
  end
  def filename
    original_filename.chomp(File.extname(original_filename)) + '.mp4'
  end
  storage :file
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end
end

谢谢你!

dsekswqp

dsekswqp1#

您应该能够使用model方法访问上载程序中的示例。
你还没有定义@title-它是nil。你可以用下面的代码创建一个条件版本。

class VideoUploader < CarrierWave::Uploader::Base
  version :tblend, if: :tblend_glitch? do # use a better version name
    process encode_video: [:mp4,
      resolution: "1280x960",
      custom: %w(-to 5 -vf scale=-2:720,tblend=all_mode=difference,tblend=all_mode=difference,tblend=all_mode=difference,spp=4:10,tblend=all_mode=average,tblend=all_mode=difference,tblend=all_mode=difference,tblend=all_mode=difference,spp=4:10,tblend=all_mode=average,tblend=all_mode=difference,tblend=all_mode=difference,tblend=all_mode=difference,spp=4:10,tblend=all_mode=average,tblend=all_mode=difference,tblend=all_mode=difference,tblend=all_mode=difference)]
  end

   # rest of the code

  private

  def tblend_glitch?
    model.title == 'tblend_glitch'
  end
end

参考:https://github.com/carrierwaveuploader/carrierwave#conditional-versions

l0oc07j2

l0oc07j22#

理论上,你可以从上传程序访问model及其属性。但是,看起来挂载的上传程序在其他属性被分配之前被调用。
对我来说,首先用常规参数创建模型,然后在第二步中分配加载了上传程序的属性(在您的例子中是:file),然后我就可以从上传程序中正确读取所有model属性。
在您的情况下,控制器中的内容如下所示:

@video = Video.new(video_params.except(:file))
@video.file = video_params[:file]   # Invoke uploader last to access the other attributes

相关问题