2

I would like to make my app upload multiple files with Shrine, but one doc suggests two file_fields whereas the other suggests only one. After posting a question to their discourse forum, it was suggested that I hide the one named files[]. Whether I do this or not, the first file_field always fails to render. Why does this field not display?

<%= form_for @item, html: { enctype: "multipart/form-data" } do |f| %>
 <%= f.fields_for :photos do |i| %>
  <%= i.label :image %>
  <%= i.hidden_field :image, value: i.object.cached_photos_data, class: "upload-data" %>
  <%= i.file_field :image, class: "upload-file" %> /// why is this not rendering?
 <% end %>
 <%= file_field_tag "files[]", multiple: true %> // what purpose does this one serve?
 
 <%= f.text_field :title %>
      
 <%= f.submit "Submit" %>    
<% end %>

Models:

class Item < ApplicationRecord
 has_many :photos, as: :imageable, dependent: :destroy
end

class Photo < ApplicationRecord
 include ImagesUploader::Attachment(:image)
 belongs_to :imageable, polymorphic: true
 validates_presence_of :image
end

Controller:

class ItemsController < ApplicationController
 def new
  @item = current_user.items.new
 end

 def create
  @item = current_user.items.create(item_params)
  @item.save
 end

 private
 def item_params
  params.require(:item).permit(:title, photos_attributes: { image: [] })
 end
end
calyxofheld
  • 1,538
  • 3
  • 24
  • 62
  • 2
    In 2020 active_storage is recommended for uploading files in Ruby on Rails https://edgeguides.rubyonrails.org/active_storage_overview.html# – Yshmarov Oct 02 '20 at 16:37
  • 1
    @Yshmarov Active Storage is terrible once you start working with it. it generates versions on the fly (why anyone would want to do this in production is beyond me), it gives less control over storage in S3, and it performs unnecessary db queries. it's not good. the professional recommendation everywhere is to go for shrine. – calyxofheld Oct 02 '20 at 17:17

1 Answers1

1

Read the first link carefully: It says that the single field (i.file_field :image) is used to display existing images (which is why it's wrapped in f.fields_for :photos in the example) and the multiple field (file_field_tag "files[]", multiple: true) is used to upload new files. So if your @item doesn't have an :image, then the field isn't shown.

Let me know if this needs any further clarification – happy to help!

Clemens Kofler
  • 1,878
  • 7
  • 11
  • 1
    also you can `build` the relationship however many time in your controller. So in the new action you can do `3.times { @item.photos.build }` and that will start the relationship and allow the fields to show in the form – Int'l Man Of Coding Mystery Oct 05 '20 at 17:05