我与Carrierwave建立了多态关系。
我想根据他们的模型创建不同版本的图像。因此,每个模型都会声明尺寸,Carrierwave将使用它们来处理图像。 This article已经解释了如何很好地完成它。
我希望在我的上传器中获取model.imageable
以获取特定模型的IMAGE_SIZES
数组,然后再创建图像版本。
目前,我收到以下错误:
uninitialized constant NilClass::IMAGE_SIZES
关于这个问题:resize_to_fit *(model.imageable.class::IMAGE_SIZES[size])
如何在上传器中获取model.imageable
。在使用多态关系时,有没有更好的方法来实现这一点?
app/models/image.rb
class Image < ApplicationRecord
mount_uploader :picture, ImageUploader
belongs_to :imageable, polymorphic: true, optional: true
end
app/models/article.rb
class Article < ApplicationRecord
has_many :images, as: :imageable
accepts_nested_attributes_for :images
IMAGE_SIZES = {
thumb: [132, 132]
}
end
app/uploaders/image_uploader.rb
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
storage :file
process dynamic_resize_to_fit: :default
version :thumb do
process dynamic_resize_to_fit: :thumb
end
def dynamic_resize_to_fit(size)
resize_to_fit *(model.imageable.class::IMAGE_SIZES[size])
end
def method_missing(method, *args)
return false if method.to_s.match(/has_(.*)_size\?/)
end
def setup_available_sizes
model.imageable.class::IMAGE_SIZES.keys.each do |key|
self.class_eval do
define_method("has_#{key}_size?".to_sym) { true }
end
end
end
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end