LoginSignup
0
0

More than 1 year has passed since last update.

CarrierWave NoMethodError (undefined method `map' for #<ActionDispatch:

Posted at

問題点

React (FormData) と Rails (CarrierWave) を使用して、
フロントエンド側から複数の画像を配列にまとめてバックエンド側に送信し、画像を保存しようとしたところ、
以下のエラーが発生しました。

NoMethodError (undefined method `map' for #<ActionDispatch::Http::UploadedFile:0x0000000113821568 @tempfile=#<Tempfile:/var/folders/wc/bdwclb6j70qd2qbrhj4xbz_w0000gn/T/RackMultipart20230111-78142-3co5tx.png>, @original_filename="スクリーンショット 2022-11-19 20.29.07.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"post[image][]\"; filename=\"\xE3\x82\xB9\xE3\x82\xAF\xE3\x83\xAA\xE3\x83\xBC\xE3\x83\xB3\xE3\x82\xB7\xE3\x83\xA7\xE3\x83\x83\xE3\x83\x88 2022-11-19 20.29.07.png\"\r\nContent-Type: image/png\r\n">
      @uploaders = new_files.map do |new_file|
                            ^^^^
Did you mean?  tap):

React側のコードは以下のようになっています。

react
    const data = new FormData();
    images.map((image) => {
      data.append("post[image][]", image);
    });

Rails 側のコードは以下のようになっています。

rails
  def create    
    post_params[:image].each do |image|
      post = Post.new(image: image)
      if post.save
      else
        render json: post.errors
      end
    end
  end

  private
  def post_params
    params.require(:post).permit({image: []})
  end

解決方法

CarrierWave の mount_uploaders を mount_uploader に変更することで、このエラーを解決できます。
配列内の画像を分解して保存する場合は、mount_uploaderのsを取る必要があるようです。

post model
class Post < ApplicationRecord

  mount_uploader :image, ImageUploader #←mount_uploadersではなくmount_uploaderにする
  
  validates :image, presence: true
end

以上が、CarrierWave の NoMethodError (undefined method `map' for #<ActionDispatch: の解決方法でした。

参考

0
0
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
0
0