我有以下三个模型:
class Product < ActiveRecord::Base
has_many :images, :as => :imageable
end
class Category < ActiveRecord::Base
has_many :images, :as => :imageable
end
class Image < ActiveRecord::Base
mount_uploader :image, ImageUploader
belongs_to :imageable, :polymorphic => true
end
我的图像控制器如下所示:
class Admin::ImagesController < AdminController
before_filter :find_imageable
def new
@image = @imageable.images.new
end
def create
if @image = @imageable.images.create(params[:image])
redirect_to admin_images_path(:imageable_type => @imageable.class, :imageable_id => @imageable.id)
else
render 'new'
end
end
private
def find_imageable
klass = params[:imageable_type].capitalize.constantize
@imageable = klass.find(params[:imageable_id])
end
end
一切都按预期工作,但现在我想根据关联类型的类型调整图像大小:
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
storage :file
version :thumb, :if => :is_product? do
process :resize_to_fill => [100, 100]
end
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
protected
def is_product? image
model.imageable.class == 'Product' # => imageable is nil!
end
end
问题是,“模型”与上传器中的图像没有关联。当我检查模型时,它是这样的:
#<Image id: nil, name: "test", image: nil, imageable_id: nil, imageable_type: nil, created_at: nil, updated_at: nil>
有什么想法吗?