2
votes

I've used the following technique to successfully upload multiple files using paperclip (without using nested attributes)

Project.rb

has_many :photos, :dependent => :destroy

Photo.rb

has_attached_file :asset, :styles => { :medium => "300x300>" }
belongs_to :project

photos/new.html.erb

<%= form_for @photo, :html => { multipart: true } do |f| %> 


 <div>
    <%= f.label :asset, 'Project Photos', class: 'label1' %>

    <%= file_field(:photo, :asset, :multiple => true) %>

</div>

<div>
 <%= f.submit "Add photos to project" %>
</div>

Photos_controller:

def create

 @project = Project.find(params[:id])
 @client = Client.find(params[:id])


  params[:photo][:asset].each do |file|
  @photo = @project.photos.build(:asset => file)
  if
    @photo.save.......

photos/show.html.erb

<div>
  <% @project.photos.each do |p| %>

  <%= image_tag(p.asset.url(:square)) %> 

  <%= check_box_tag 'destruction[]', p.id %>

<% end %>

Routes file:

resources :photos do
  collection do
   delete 'destroy_multiple'
 end
end

I'm trying to create an array of id's based on checkboxes to be passed to the destroy_multiple action in the photos controller. params[:destruction] does yield the correct ids.

What would be the most efficient way of telling the destroy_multiple action to delete only those assets whose id's are in the destruction array?

Many thanks for your time.

1

1 Answers

2
votes

destroy_all

Paperclip is just a link between the saved asset (image/video), and your ORM (in our case ActiveRecord).

This means that you should still be able to perform all the queries you want through your standard AR methods (destroy_all etc), with Paperclip removing the relevant assets as you require.

As such...

#config/routes.rb
resources :photos do
   delete :destroy_multiple, action: :destroy, on: :collection
end

#app/controllers/photos_controller.rb
class PhotosController < ApplicationController
   def destroy
       ids = params[:destruction] || params[:id]
       Photo.destroy_all ids if ids
   end
end

Paperclip will handle the rest!