我正在使用单个 Image
模型来存储有关不同其他模型使用的图像的信息(通过多态关联)。
我想根据关联的模型更改此模型上的上传器,以便为不同模型提供不同版本。
例如,如果 imageable
是 Place
,安装的上传器将是 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_place
和 thumb_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/