So I'm using paperclip in my rails 3.1 app,
I am adding images to an item using relationships so that I can have multiple images per item.
What I'd like to do is be able to click the browse button and select multiple files using just the single field. Rather then having to go one image at a time for each field.
Anybody know how to do this, or have a great option for doing this that doesn't require flash plugins?
I'm using just one controller, no associations (mine is just for uploading multiple images to a gallery), but I've managed to do what you're asking. You will need to adapt it to work with your relationship, but it works great for me (although won't work in IE), I'm sure it breaks some rails conventions though, but it's the only way I could figure to build the functionality.
The first step is to set the upload field to accept multiple files using the HTML5 multiple tag:
<%= f.file_field :photo, multiple: 'multiple' %>
Or, if you're using simple_form like me:
<%= f.input :photo, input_html: { multiple: 'multiple' } %>
The next step is to change the create controller action to accept and process the multiple files. This is the bit I'm sure some will object to, but hey, it works!
def create
params[:photo][:photo].each do |photo|
@params = {}
@params['photo'] = photo
@photo = Photo.new(@params)
if [email protected]
respond_to do |format|
format.html { redirect_to new_photo_path, error: 'An error occured uploading.' }
end
end
end
respond_to do |format|
format.html { redirect_to photos_path, notice: 'Photos were successfully uploaded.' }
end
end
It's simpler than it looks - for me the controller name is photo
and so is the field name, which explains the params[:photo][:photo]
. It basically just takes the :photo
attribute of the request (where the controller would normally expect one file) and iterates over the files that have been uploaded creating a new Photo
for each and setting the photo
attribute of @params
to be each file in turn then attempting to save this as a new Photo
and alerting if an error occurs, otherwise once finished it will redirect to show the photos.
As I say, this works great for me and I hope it's helpful for you too :)
Edit If this hasn't been helpful, can you let me know why? Just ignoring the message after someone spent time helping isn't going to get other people to want to help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With