Ruby on rails 验证失败时重新加载回形针文件上载

Ruby on rails 验证失败时重新加载回形针文件上载,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,我不熟悉rails。我目前正在为Rails 3中的一个模型设置回形针。当其中一个表单域验证失败时,它将无法重新加载我上传的图像。它会要求用户重新上传。它看起来对用户不友好 我想做两件事来解决这个问题。如果所有字段都填写正确,我希望将其存储在我的应用程序中(系统文件夹与通常的回形针一样)。如果字段验证失败,则希望暂时将图像存储在单独的文件夹中,直到保存 我走的路对吗?还有什么简单的方法可以做到这一点吗?不幸的是,只有成功保存包含文件的模型后,回形针才会保存上载的文件 我相信最简单的选择是使用jav

我不熟悉rails。我目前正在为Rails 3中的一个模型设置回形针。当其中一个表单域验证失败时,它将无法重新加载我上传的图像。它会要求用户重新上传。它看起来对用户不友好

我想做两件事来解决这个问题。如果所有字段都填写正确,我希望将其存储在我的应用程序中(系统文件夹与通常的回形针一样)。如果字段验证失败,则希望暂时将图像存储在单独的文件夹中,直到保存


我走的路对吗?还有什么简单的方法可以做到这一点吗?

不幸的是,只有成功保存包含文件的模型后,回形针才会保存上载的文件


我相信最简单的选择是使用javascript进行客户端验证,这样就不需要所有的后端配置/黑客攻击。

我不得不在最近的一个项目中解决这个问题。这有点粗糙,但它可以工作。我曾尝试在模型中使用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: ''}