2

我有以下三个模型:

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>

有什么想法吗?

4

2 回答 2

0

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

于 2013-05-07T16:33:46.080 回答
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”方法,则默认启用所有版本...

于 2013-11-18T21:49:36.090 回答