LoginSignup
4
1

More than 1 year has passed since last update.

Rails7で複数画像file_filedを使っていると空画像が入る対策

Last updated at Posted at 2022-03-08

背景

Rails6.1からRails7に上げたとき、画像フィールドの動作がおかしくなったのを修正した備忘録。

RailsアプリはHerokuで動かしており、画像のアップロードにCarrierWaveとCloudinaryを使っている。
development環境では実際にCloudinaryには上げず、手元のローカルファイルとして動作させている。
画像のためにRailsのActiveStorageは使っていない。
また、画像のアップロードは複数画像を使うためにfile_filed multiple: trueを使っていた。

起こったこと

複数画像を許可しているfile_filedを使って画像をアップロードすると、想定していない空画像が一緒にアップロードされてしまう。

スクリーンショット 2022-03-08 170300.png

consoleからparamsを確認すると、先頭に謎の空文字があるのが確認できる。

image.png

原因

Rails7からActiveStorageの便利さのために、multiple: trueで呼び出したfile_filedが空の入力フィールドを一緒につくるようになった。
ActiveStorageによるファイル添付操作が上書きのため、update時にすでに添付されていたファイルを置くためのフィールドらしい。

image.png

自分のアプリではActiveStorageを使っていなかったため、上記のような不具合となった。

解決方法その1

既存ファイルconfig/application.rbや新規ファイルconfig/initializers/multi_file_field.rbに設定を追加する。

config/application.rb
config.active_storage.multiple_file_field_include_hidden = false

解決方法その2

file_fieldmultiple: true付きで呼び出すときに、include_hidden: falseをつける

app/views/sakes/_form.html.erb
<%= form.file_field(:photos,
                    multiple: true,
                    include_hidden: false,
                    class: "form-control col-12",
                    accept: "image/*;capture=camera") %>

参考

4
1
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
4
1