rails file_field not showing

1.1k views Asked by At

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
1

There are 1 answers

1
Clemens Kofler On

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!