当验证失败时重新加载Paperclip文件上传

4
我是新手Rails开发者。我正在为Rails 3模型设置Paperclip。当表单字段验证失败时,它无法重新加载我的上传图片。它要求用户重新上传,这不太友好。
我想要做两件事来解决这个问题。如果所有字段都填写正确,我想把它存储在我的应用程序中(像通常的Paperclip一样存储在系统文件夹中)。如果字段验证失败,我希望将图像暂时存储在单独的文件夹中,直到它被保存。
我走的路线是正确的吗?还是有更简单的方法来做到这一点?
2个回答

1

很遗憾,Paperclip只有在包含文件的模型成功保存后才保存上传的文件。

我认为最简单的方法是使用JavaScript在客户端进行验证,这样就不需要进行所有的后端配置/黑客攻击。


0

我最近在一个项目中不得不修复这个问题。虽然有点繁琐,但它确实有效。我尝试在模型中使用after_validation和before_save调用cache_images(),但由于某种原因,在创建时失败了,我无法确定原因,所以我只能从控制器中调用它。希望这能为其他人节省一些时间!

模型:

class Shop < ActiveRecord::Base    
  attr_accessor :logo_cache

  has_attached_file :logo

  def cache_images
    if logo.staged?
      if invalid?
        FileUtils.cp(logo.queued_for_write[:original].path, logo.path(:original))
        @logo_cache = encrypt(logo.path(:original))
      end
    else
      if @logo_cache.present?
        File.open(decrypt(@logo_cache)) {|f| assign_attributes(logo: f)}
      end
    end
  end

  private

  def decrypt(data)
    return '' unless data.present?
    cipher = build_cipher(:decrypt, 'mypassword')
    cipher.update(Base64.urlsafe_decode64(data).unpack('m')[0]) + cipher.final
  end

  def encrypt(data)
    return '' unless data.present?
    cipher = build_cipher(:encrypt, 'mypassword')
    Base64.urlsafe_encode64([cipher.update(data) + cipher.final].pack('m'))
  end

  def build_cipher(type, password)
    cipher = OpenSSL::Cipher::Cipher.new('DES-EDE3-CBC').send(type)
    cipher.pkcs5_keyivgen(password)
    cipher
  end

end

控制器:

def create
  @shop = Shop.new(shop_params)
  @shop.user = current_user
  @shop.cache_images

  if @shop.save
    redirect_to account_path, notice: 'Shop created!'
  else
    render :new
  end
end

def update
  @shop = current_user.shop
  @shop.assign_attributes(shop_params)
  @shop.cache_images

  if @shop.save
    redirect_to account_path, notice: 'Shop updated.'
  else
    render :edit
  end
end

视图:

= f.file_field :logo
= f.hidden_field :logo_cache

- if @shop.logo.file?
  %img{src: @shop.logo.url, alt: ''}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接