有条件地使用carrierwave重新调整大小,具体取决于多态关联

时间:2013-03-24 14:24:18

标签: ruby-on-rails carrierwave polymorphic-associations

我有以下三种模式:

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

问题是,'model'与上传者中的imageable没有关联。当我检查模型时,这就是它的样子:

#<Image id: nil, name: "test", image: nil, imageable_id: nil, imageable_type: nil, created_at: nil, updated_at: nil>

有什么想法?

2 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。我确实找到了workaround,但我仍然想知道是否有更好的方法来解决这个问题。

答案 1 :(得分:0)

我通常会这样做

  version :thumb, :if => :thumb_version_enabled? do
    process :resize_to_fit => [100, 100]
  end

  version :big, :if => :big_version_enabled? do
    process :resize_to_fill => [600,600]
  end

  def include_version?(v)
    if self.model.respond_to?("only_versions")
      self.model.only_versions.collect(&:to_s).include? v.to_s
    else
      true
    end
  end

  protected 

  def method_missing(method_name, *args, &block)
    return super unless /^(.*)_version_enabled(=?)/ =~ method_name
    return include_version?(method_name.to_s.gsub("_version_enabled?","").gsub("_version_enabled",""))
  end

在目标模型中(安装了上传器)我将定义一个定义启用版本的方法

class Product < ActiveRecord::Base

  ##....omiss
  mount_uploader :image, ImageUploader

  def self.only_versions
    [:thumb, :big, :small, :original]
  end

  def only_versions
    self.class.only_versions
  end
end

如果是多态关联,您可以将方法委托给关联模型

class Image < ActiveRecord::Base
  mount_uploader :data, ImageUploader

  belongs_to :imageable, :polymorphic => true

  def only_versions
    if self.imageable && self.imageable.respond_to?("only_versions")
      self.imageable.only_versions
    else
      ImageUploader.versions.keys
    end
  end

如果缺少方法“only_versions”,则默认启用所有版本...

这是一项正在进行中的工作,感谢您的帮助!

抱歉我的英语很差