In my rails app, I wish for the users to be able to upload multiple files at once.
I am using the carrierwave gem
gem 'carrierwave', github: 'carrierwaveuploader/carrierwave'
On the master branch which supposedly supports the multiple: true
found out in my internet searching desperation about the necessary addition of optional: true
in my model for my attachment.
I'm using mysql so I can't use an array type in my database, but I've set up a has_many
, belongs_to
relationship between Request
and Request_Attachment
in my database.
my form:
<%= f.fields_for :request_attachments do |ra| %>
<div class="row" id="uploader">
<div class="col-xs-12">
<label class="btn btn-info"> Upload Files
<%= ra.file_field :file, multiple: true, name: "request_attachments[file][]", :style => "display: none" %>
</label>
</div>
</div>
<% end %>
my controller
@request = Request.new(request_params)
if @request.save
if params[:request][:request_attachments]
params[:request][:request_attachments]['file'].each do |f|
@request_attachment = @request.request_attachments.create!(:file => f)
end
end
flash[:success] = "Your request was submitted successfully, check your email for a confirmation message."
redirect_to action: 'index', status: 303
else
render :new
end
def request_params
params.require(:request).permit(:jobtitle, :requester, :status, request_attachments_attributes: [:id, :request_id, :file])
end
my models:
Request:
class Request < ApplicationRecord
has_many :request_attachments
accepts_nested_attributes_for :request_attachments
end
Request_Attachments:
class RequestAttachment < ApplicationRecord
mount_uploader :file, FileUploader
belongs_to :request, optional: true
end
I have tried variations of the form, like taking out the name
portion.
When I remove the multiple: true
portion, it will work perfectly, but it does not work with the multiple
option.
I'm not quite sure where the issue may be, so any help would be great.
What is happening now is that the request gets saved, but
Only 1 request_attachment is created, and
The filename of the request_attachment is
nil