Ruby on rails 带Carrierwave的动态上传器
我使用一个Ruby on rails 带Carrierwave的动态上传器,ruby-on-rails,carrierwave,Ruby On Rails,Carrierwave,我使用一个图像模型来存储关于其他不同模型使用的图像的信息(通过多态关联) 我想根据相关的型号更改此型号的上载程序,以便为不同的型号提供不同的版本 例如,如果可成像是一个位置,则安装的上传器将是一个位置上传器。如果没有PlaceUploader,它将是默认的ImageUploader 目前我有: class Image < ActiveRecord::Base belongs_to :imageable, polymorphic: true mount_uploader :image
图像
模型来存储关于其他不同模型使用的图像的信息(通过多态关联)
我想根据相关的型号更改此型号的上载程序,以便为不同的型号提供不同的版本
例如,如果可成像
是一个位置
,则安装的上传器将是一个位置上传器
。如果没有PlaceUploader
,它将是默认的ImageUploader
目前我有:
class Image < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
mount_uploader :image, ImageUploader
end
有没有办法做到这一点?还是根据关联的型号提供不同版本的更好方法
编辑 我用一个
图像上传器找到了另一个解决方案:
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
class ImageUploader
正如您所见,我的两个版本分别命名为thumb\u place
和thumb\u user
,因为如果我同时命名这两个版本,则只会考虑第一个版本(即使它不满足条件).我需要实现相同的逻辑,我有一个单一的图像模型,并基于多态关联来装载不同的上传程序
最后,我在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
类映像
只是一个想法,您希望通过单独的上传来实现什么?目标是根据不同的型号提供不同的图像版本。实际上,我正在使用另一个解决方案(请参见原始问题的编辑)。警告:这不是线程安全的,因此如果您想使用,需要确保您已将rails配置为不使用线程(这将影响您的部署配置文件)。
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