11
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

carrierwaveでバリデーション失敗後に画像を保持するときの覚書

Posted at

概要

input type="file"のは初期値の設定ができないのでにバリデーション失敗後の考慮が面倒ですよね?
ただ、アップローダーにcarrierwaveを使っている場合は非常に楽に実装ができます

解説

画像アップロード時に{column_name}_cacheという名前でhidden_fieldをプラスしてあげればOKです.

view

= form_for @hogehoge |form|

  // 値がセットされている場合は画像を表示
  = image_tag @hogehoge.hogehoge_image.url if @hogehoge.hogehoge_image.present?
  = f.file_field :hogehoge_image
  // 値の保持
  = f.hidden_field :hogehoge_image_cache
  = f.submit

cacheのディレクトリも任意で設定可能

class HogeImageUploader < CarrierWave::Uploader::Base

....省略
  # cacheでアップロードする画像の設定
  def cache_dir
    "cache"
  end
end

cacheをS3にアップロード(fog)
cache_storageはCarrierWaveのgem versionが古いと
no methodエラーになるので注意

config/initializers/carrierwave.rb
CarrierWave.configure do |config|

   ....省略
  config.cache_storage = :fog
end

参考

carrierwaveuploader/carrierwave
https://github.com/carrierwaveuploader/carrierwave

HTML input要素
http://www.ne.jp/asahi/hishidama/home/tech/web/html/input.html

11
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?