Tim*_*ola 6 ruby-on-rails carrierwave
我使用单个Image模型来存储有关不同其他模型使用的图像的信息(通过多态关联).
我想根据相关的模型更改此模型上的上传器,以便为不同的模型提供不同的版本.
例如,如果imageable是a Place,则安装的上传器将是a PlaceUploader.如果没有PlaceUploader,那将是默认值ImageUploader.
目前我有:
class Image < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
mount_uploader :image, ImageUploader
end
Run Code Online (Sandbox Code Playgroud)
理想情况下,我希望:
# This is not supported by CarrierWave, just a proof of concept
mount_uploader :image, -> { |model| "#{model.imageable.class.to_s}Uploader".constantize || ImageUploader }
Run Code Online (Sandbox Code Playgroud)
有没有办法实现这一目标?或者根据相关模型获得不同版本的更好方法?
我找到了另一种解决方案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
Run Code Online (Sandbox Code Playgroud)
正如您所看到的那样,我的两个版本被命名thumb_place,thumb_user因为如果我将它们命名为两者,则thumb只会考虑第一个版本(即使它不满足条件).
小智 1
我需要实现与单个图像模型相同的逻辑,并基于多态关联来安装不同的上传器。
最后我在 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
Run Code Online (Sandbox Code Playgroud)