問題描述
在 rails/paperclip 中處理一系列圖像 (handling an array of images in rails/paperclip)
I am allowing a user on my website to upload up to three images. So in my form I have these elements:
<label>Additional Images*<span class="note">(Maximum: 3, 200 pixels wide)</span></label>
<%= f.file_field :images, { :multiple => "", :accept => "image/*" } %>
<div id="images"></div>
I have some javascript that validates only 3 images or less were selected, and it also creates thumbnails of the images and adds them as a child to div#images. When a user submits the form, then the :images parameter is populated with an array of image information that looks like this:
[ #<ActionDispatch::Http::UploadedFile:0x00000007269588
@original_filename="test_banner.jpeg",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"custom_form[images][]\"; filename=\"test_banner.jpeg\"\r\nContent-Type: image/jpeg\r\n",
@tempfile=#<File:/tmp/RackMultipart20120726-7134-3hqdve>>,
#<ActionDispatch::Http::UploadedFile:0x00000007269510
@original_filename="test_portrait.jpeg",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"custom_form[images][]\"; filename=\"test_portrait.jpeg\"\r\nContent-Type: image/jpeg\r\n",
@tempfile=#<File:/tmp/RackMultipart20120726-7134-18fcs0m>>,
#<ActionDispatch::Http::UploadedFile:0x00000007269498
@original_filename="test_signiture.jpeg",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"custom_form[images][]\"; filename=\"test_signiture.jpeg\"\r\nContent-Type: image/jpeg\r\n",
@tempfile=#<File:/tmp/RackMultipart20120726-7134-1q5fy2f>> ]
In my model, I have 3 attributes:
has_attached_file :image1,
...
has_attached_file :image2,
...
has_attached_file :image3,
...
I am trying to get it so the information from the images parameter that is sent with the form is split up and sent to the respective image attribute in the model, and if the user only uploaded one or two images the other attributes are nil. Is there a way I can make this work in rails using paperclip?
參考解法
方法 1:
I'd strongly suggest you just make 3 x file_fields. Then everything lines up and you're validations will all just work. I know it's not quite as slick, but for 1-3 images... Not really a big deal.
(by Huub Mons、TomDunning)