Again, I am trying to make this the most understandable code, without any regard whatsoever for elegance. In a previous post I made a do-nothing uploader, just to get some feel for the whole HTML5 file upload process. I recommend that you also make one and play with it to get a good feel for what goes on.
This time, we’re actually going to upload, attach, and display files using Paperclip and Rails 4.
The Summit County Engineer keeps track of Road Records. A Road Record can have a bunch of attached files of varying formats, e.g. tif, pdf, jpg, and doc. There’s a bunch of fields about which road, which section, what kind of work, etc. These, you can ignore.
For this tutorial (and my app,) I’m going to call the attached files Road Record Assets.
For the most part, this is just typical Paperclip. Most of the non-typical work gets done in the road_records_controller, so let’s look at that first. (Rails 4: turn off protect_from_forgery for the add_assets function)
It just adds a new RoadRecordAsset for every file it gets. The fact that the file gets stored in /tmp/ for a bit gives you the chance to rename it, sanitize it, or whatever before it actually gets attached. Don’t forget to add the route:
The RoadRecord model is simplicity itself.
And the RoadRecordAsset model is nearly as simple.
Notice that you can do all the usual Paperclip magic, just as you’re used to.
All that’s left is the upload part, which is very similar to what was shown in the last post:
I scrounged all over the web for bits of this; hopefully, you won’t have to. Thanks to all those who posted demos, tuts, and gems!