LoginSignup
57
59

More than 5 years have passed since last update.

CarrierWaveでUPDATE時に前回アップロードした画像を消さないようにする。

Posted at

例えばユーザーのプロフィール画像で使用している際、

models/user.rb
class User < ActiveRecord::Base
  ...
  mount_uploader :image, ImageUploader
end

/users/:id/editにアクセスするとformファイル選択ボックス(file_field)には前回アップロードした画像は設定されていないので、この状態でupdate(PATCH/PUT /users/:id)を行うと前回アップロードした画像が消えてしまう。

image_cacheを追加する

既に画像が存在する場合はキャシュを作成する

controllers/users_controller.rb
  # GET /users/1/edit
  def edit
    @user.image.cache! unless @user.image.blank?
  end

画像をアップロードするViewでhiddenタグにキャッシュを追加する

views/users/edit.html.erb
 <%= f.label :image, "画像" %>
 <%= f.file_field :image %>
 <%= f.hidden_field :image_cache %>

Strong Parametersへ:image_cacheを追加後updateすると
画像を変更していない場合は、前回アップロードした画像は消えない。

57
59
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
57
59