File Uploads with Rails 3, Plupload, and CarrierWave

You may know that I've been working on Be The Builders for a while now. When it came time to build in some functionality for file uploads, I just started to cringe. I searched for a while on ways to get it done, but I was hoping for something a little easier without the need for middleware. I came across Plupload and figured I'd give it go for integrating into Rails 3. Ultimately, it was pretty easy and painless. I'll walk you through the process. Just to note, I was using CarrierWave to handle the file uploads on the Rails side and Mongoid as my ORM.

  • Step 1 - Download Plupload and copy the js folder into your javascripts directory. I'm not going to go through all of the options for Plupload, just what it takes to get you going. You can figure out all of the options in Plupload's documentation.
  • Step 2 - Add the appropriate javascript_include_tag to your view. Since I only had one action that was going to handle the creation of the images, I just put it in my new.html.erb view.
  • Step 3 - Now comes the part where we need to add some of the javascript to get the Plupload controls to show up on the page. I followed the custom example that was posted on their website. The important points that you need to know about the javascript below is the multipart and multipart_params options. Without those, CarrierWave is going to throw all sorts of errors when you try to upload the file. Also important to note is the use of the authenticity token in the multipart_params. It's just something that needs to be done to keep the session legit The html in the view is the same as the Plupload documentation example.
  • Step 4 - Get your CarrierWave uploader mounted to your model. In this example, this is what I have: Now if you're using Rails 3 like I am, make sure you do a require 'carrierwave' and require 'carrierwave/orm/mongoid' at the top of your application.rb file. Also, you'll have to pull the latest code from github. At the time of this writing, the carrierwave gem does not support Rails 3.
  • Step 5 - Code up the create action in your controller. It could be something as simple as this: Mine doesn't look that that, it's a little messy and I didn't want to paste all of it here.
  • Step 6 - Relax and have a much deserved drink. You're done!

I found this process to be extremely easy and with Plupload I now have the option to use many different methods (flash, silverlight, html5, etc) to get files uploaded to Rails. Hope this quick tutorial helps you guys.

blog comments powered by Disqus