Hey there, I want to be able to upload multiple images at once on my
website. I can only upload one image at a time at the moment. Can
anybody lead me in the right direction? Here’s my code
In order to do this (no matter which file attachment system you choose)
you will need to refactor your application slightly. You need a model
instance per image uploaded, so the usual way to do this is with a
nested form. You create a form on a parent object that has_many of the
image objects. If the Listing model is the parent, then you can add an
Image model to belong to that listing, in a one-to-many relationship.
Then you set up the following (this is pseudocode, off the top of my
head, not guaranteed to work as written, but the right idea, IMO):
class Listing < ActiveRecord::Base
has_many :images
accepts_nested_attributes_for :images, allow_destroy: true, reject_if:
:all_blank
end
class Image < ActiveRecord::Base
belongs_to :listing
has_attached_file :image
end
class ListingsController < ApplicationController
… all the usual CRUD actions here
private
def listing_params
params.require(:listing).permit(:name, :description, :price,
images_attributes: [:id, :image, :_destroy])
end
end
And finally, in your form_for @listing, you need to create a very
particularly named field in order to get this all to work together:
That last part is ripped out of working code using Paperclip.
Things to note here:
It’s using the file_field_tag generator (long-hand) rather than the
f.file_field that you may be used to. This is so that the name can be
exactly what it needs to be to “trick” the accepts_nested_attributes_for
helper into accepting the attached files.
The multiple: true thing means that you will need a modern browser to
use this (HTML5 feature).
The empty square-brackets in the middle of the name are the “secret
sauce” that cause the individual files in the multiple file form element
to be sent as separate files, rather than the last one “winning” or the
data being concatenated and sent as form post body instead.
This type of field is only useful on an initial create or upload
screen, not if you want to edit each of the attached files individually.
I would put this particular form on the #new screen.
I went through all of your steps. What should I write on my view page?
If you want to show all the images for a listing, the simplest thing is:
<%- @listing.images.each do |image| %>
<%= image_tag image.image_url %>
<%- end %>
Now there are lots of other refinements you could add to this – sizing
the images, extra HTML around each one, setting their order, etc. – but
this will get you started.
On 11 February 2016 at 03:08, Walter Lee D. [email protected]
wrote:
has_attached_file :image
And finally, in your form_for @listing, you need to create a very particularly
named field in order to get this all to work together: