Topic: Handling attachments

Hello guys,

I have a rails app that uses polymorphic attachments for several objects. Currently I'm using nested forms to create uploads when editing the parent object.

This works as it should, but I stumbled upon blog post describing new HTML5 drag&drop uploading as it's already known from the Gmail webinterface, for example.

I'd like to offer such a functionality aswell, but I have some questions about the actual saving of uploaded items.

Usually you have a form and select some files (images in my case) and then you submit which starts the  actual upload. The parent object gets saved first and then the ID will be put in the attachment records asuming a model like this:

 has_many :attachments, :as => :attachable, :class_name => "Upload", :dependent => :destroy

Now this won't work with drag&drop uploading, because the file upload happens right after selecting the file and the parent object doesn't yet exist.

Re: Handling attachments

I've not used drag&drop but i would have it so that the js which sends the file data gets the id of the newly created attachment object back from the server-side action it calls to save the file, and writes it into a hidden field in the form called "parent_model_name[attachment_ids][]" (make a new one of these for every saved file)

Then when the form is submitted, the parent object gets "attachment_ids=" called with the ids of the attachment objects and properly makes the association then in the normal railsy way.

You then have to deal with 'hanging' attachments, ie ones where the parent never gets submitted, and they are not owned by any other objects.  But, you could have a cron job which runs once a day, which runs a rake task to tidy these up, eg delete any attachments with no parent that are more than a day old.

Last edited by Max Williams (2011-07-11 05:50:23)

###########################################
#If i've helped you then please recommend me at Working With Rails:
#http://www.workingwithrails.com/person/ … i-williams

Re: Handling attachments

Thank you very much for your input. I'll give this approach a try.