ruby-on-rails - 带有 Carrierwave 的动态 uploader

标签 ruby-on-rails carrierwave

我正在使用单个 Image模型来存储有关不同其他模型使用的图像的信息(通过多态关联)。

我想根据关联的模型更改此模型上的上传器,以便为不同模型提供不同版本。

例如,如果 imageablePlace ,安装的上传器将是 PlaceUploader .如果没有 PlaceUploader ,它将是默认值 ImageUploader .

目前我有:

class Image < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true
  mount_uploader :image, ImageUploader
end

理想情况下,我想要:
# This is not supported by CarrierWave, just a proof of concept
mount_uploader :image, -> { |model| "#{model.imageable.class.to_s}Uploader".constantize || ImageUploader }

有没有办法实现这一目标?还是根据相关模型拥有不同版本的更好方法?

编辑

我使用一个 ImageUploader 找到了另一种解决方案:
class ImageUploader < BaseUploader

  version :thumb_place, if: :attached_to_place? do
    process resize_to_fill: [200, 200]
  end

  version :thumb_user, if: :attached_to_user? do
    process :bnw
    process resize_to_fill: [100, 100]
  end

  def method_missing(method, *args)
    # Define attached_to_#{model}?
    if m = method.to_s.match(/attached_to_(.*)\?/)
      model.imageable_type.underscore.downcase.to_sym == m[1].to_sym
    else
      super
    end
  end

end

正如你所看到的,我的 2 个版本被命名为 thumb_placethumb_user因为如果我将它们都命名为 thumb只会考虑第一个(即使它不满足条件)。

最佳答案

我需要实现相同的逻辑,我有一个单一的图像模型,并基于多态关联来安装不同的上传器。

最后我在 Rails 5 中提出了以下解决方案:

class Image < ApplicationRecord
  belongs_to :imageable, polymorphic: true

  before_save :mount_uploader_base_on_imageable

  def mount_uploader_base_on_imageable
    if imageable.class == ImageableA
      self.class.mount_uploader :file, ImageableAUploader
    else
      self.class.mount_uploader :file, ImageableBUploader
    end
  end
end

关于ruby-on-rails - 带有 Carrierwave 的动态 uploader ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18884335/

相关文章:

ruby-on-rails - 不要在 Rails 根路由中发布表单

ruby-on-rails - 无法使用:text in typed_store

ruby-on-rails - Carrierwave 后台程序 sidekiq 没有 worker

javascript - 在 Rails 中操作上传的 svg 文件

ruby-on-rails - 如何处理设备的authenticate_user!用ajax调用?

ruby-on-rails - 将我的Heroku Rails应用程序指向www而不带www只能工作一个小时吗?

ruby-on-rails - 在 Rails 中使用 Carrierwave 嵌套表单、内联上传和进度条

ruby-on-rails - 如何在 Rails 中使用 Carierwave 将两种类型的文件上传到同一个模型中?

ruby-on-rails - 如何在 Rails 中将某些内容记录在独立的日志文件中?

javascript - 使用 Carrierwave 的 ajax 请求中的照片 url