条件重新大小与载波,取决于多态关联



我有以下三个模型:

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>

任何想法吗?

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

我通常会这样做

  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"方法,则默认启用所有版本…

最新更新