LoginSignup
blue-night-blue
@blue-night-blue

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

複数画像を別レコード扱いにした際にMiniMagickを使うとundefined method `tempfile' になる

解決したいこと

  • Railsでプライベートな画像アップローダーを作成中です
  • file_fieldで複数画像を添付した場合、それぞれを別レコードとして保存する仕様にしたいです(画像にタグ付けしまくるコンセプトなので)
  • ActiveStorage経由でMiniMagickを使ってます
  • 他の方法でいけそうならそれでもOKです

発生しているエラー

NoMethodError in PostsController#create

undefined method `tempfile' for ["", #<ActionDispatch::Http::UploadedFile:0x000000010fd0b000 
@tempfile=#Tempfile:/var/folders/xy/xfg7t3952yqfz87kmgvkh2jr0000gn/T/RackMultipart20230626-44964-lmccik.jpg>, 
@content_type="image/jpeg", 
@original_filename="1.jpg", 
@headers="Content-Disposition: form-data; name=\"post[images][]\"; filename=\"1.jpg\"\r\nContent-Type: image/jpeg\r\n">]
:Array

該当するソースコード

_form.html.erb
<%= form_with(model: post) do |form| %>

  <div>
    <%= form.label :images, style: "display: block" %>
    <%= form.file_field :images, multiple: true %>
  </div>

  <div>
    <%= form.label :comment, style: "display: block" %>
    <%= form.text_area :comment %>
  </div>

  <div>
    <%= form.submit %>
  </div>
<% end %>
posts_controller.rb
 def create
    params[:post][:images].each do |image|

      image.tempfile = ImageProcessing::MiniMagick
      .source(params[:post][:images].tempfile)
      .resize_to_limit(1024, 768)
      .strip
      .call

      @post=Post.new(
        images:image,
        user_id: @current_user.id,
        comment:params[:post][:comment]
        )
      @post.save
    end
    redirect_to "/#{@current_user.name}"
  end
post.rb
class Post < ApplicationRecord
    has_many_attached :images
end

自分で試したこと

.source(params[:post][:images].tempfile)

.source(image.tempfile)

にすると、

undefined method `tempfile' for "":String

のエラーになります。

0

1Answer

params[:post][:images] に入っている配列の先頭要素がなぜか空文字列になっているので、それをスキップすれば動きそうです。

 def create
    params[:post][:images].each do |image|
      next if image == ""
      image.tempfile = ImageProcessing::MiniMagick
      .source(image.tempfile)
      .resize_to_limit(1024, 768)
      .strip
      .call

1

Comments

  1. ご回答ありがとうございます!頂いた情報を元にググってみると、
    https://qiita.com/keita44_f4/items/fd899beb1efdf6f1d648
    がヒットし、multipleすると空が入るのが仕様のようでして、

    application.rb
    config.active_storage.multiple_file_field_include_hidden = false
    

    によって解決し、上記コードは

    .source(image.tempfile)
    

    で無事、「複数添付→複数レコード」で行けました!!

Your answer might help someone💌