Rails 5:动态获取模型名称以使用Carrierwave

时间:2018-02-18 10:12:52

标签: ruby-on-rails carrierwave

如果多态关联是特定模型,我试图动态创建Carrierwave图像的版本,否则跳过它。

例如:

user.rb

class User < ApplicationRecord
  has_many :pictures, as: :imageable, dependent: :destroy
end

listing.rb

class Listing < ApplicationRecord
  has_many :pictures, as: :imageable, dependent: :destroy
end

picture.rb

class Picture < ApplicationRecord
  mount_uploader :image, ImageUploader
  belongs_to :imageable, polymorphic: true
  validates :image, presence: true
  validates_integrity_of :image
end

我试图在上传程序中执行以下操作:

class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  # Only do this if model type is Listing
  version :card do
    process resize_to_fit: [800, 800]
    process resize_to_fill: [640, 430]
  end

  # Only do this if model type is User
  version :profile do
    process resize_to_fit: [600, 600]
  end

  def extension_whitelist
    %w(jpg jpeg gif png)
  end
end

我尝试了version :profile, if: :is_user? do,然后创建了一个类似的方法:

def is_user?(picture)
  model.imageable_type.downcase == 'user'
end

但是当图片仍未保存时,model.imageable_type为nil。

我正在覆盖Devise的更新方法,以便向用户添加图片:

class Users::RegistrationsController < Devise::RegistrationsController
  def update
    super do
      pics = params[:user][:pictures]
      if pics.present?
        pics.each { |pic| resource.pictures << Picture.new(image: pic) }
      end
    end
  end
end

我也尝试过:

def update
  super do
    pics = params[:user][:pictures]
    if pics.present?
      pics.each { |pic| resource.pictures.build(image: pic) }
    end
  end
end

def update
  super do
    pics = params[:user][:pictures]
    if pics.present?
      resource.pictures = pics.map { |pic| Picture.new(image: pic) }
    end
  end
end

对于列表我正在创建这样的图像:

class ListingsController < ApplicationController
  def create
    @listing = Listing.new(JSON.parse(params[:listing]))
    @listing.owner = current_user
    @listing.pictures = params[:file].values.map { |file| Picture.new(image: file) }

    respond_to do |format|
      if @listing.save
        format.html { redirect_to listing_path(@listing), notice: 'Listing was created successfully!' }
        format.json { render :show, status: :created, location: @listing }
      else
        format.html { render :new }
        format.json { render json: @listing.errors, status: :unprocessable_entity }
      end
    end
  end
end

有没有办法动态获取模型名称来创建版本,这样我就不必为每个模型创建新的上传者(这似乎在我看来打败了具有多态图片模型的目的)。 提前谢谢!

0 个答案:

没有答案