list through.
Listing listings
<%= image_tag listing.image.url(:medium) %>
<%= listing.name %>
...
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:
<%= file_field_tag(‘listing_images_attributes_image’, multiple: true,
:name => “listing[images_attributes][][image]”) %>
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.
Once you have this working, you will need to make your #edit screen a
more traditional nested form. Read this for an example and further
ideas:
Walter