[英]Reload Paperclip file uploads when validation fails
我是鐵桿新手。 我目前正在為Rails 3中的模型設置Paperclip。當其中一個表單字段未通過驗證時,它無法再次重新加載我上傳的圖像。它要求用戶新上傳。 它看起來不友好。
我想做兩件事來解決這個問題。 如果所有字段都正確填寫我想將它存儲在我的應用程序中(系統文件夾像往常一樣回形針)。如果字段驗證失敗,想要暫時將圖像存儲在單獨的文件夾中,直到它被保存。
我正走在正確的道路上嗎? 還有什么簡單的方法嗎?
不幸的是,只有在成功保存包含該文件的模型后,Paperclip才會保存上傳的文件。
我相信最簡單的選擇是使用javascript進行驗證客戶端,因此不需要所有的后端配置/黑客攻擊。
我不得不在最近的一個項目中解決這個問題。 它有點hacky但它的工作原理。 我嘗試在模型中使用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: ''}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.