Multiple files upload with carrierwave and nested_form
I wrote this post just to show how it’s possible to get a perfectly working form with multiple files upload within a few minutes. If you need to implement multiple file attachments to a given object with only one form quickly, this example could help you.
So let’s create an example project (I used one of mine rails templates_:
Then add the gems to Gemfile:
The specified version for carrierwave is required because there is a small bug in the previous versions of carrierwave that creates some problems with nested forms.
In this example, I chose to use two simple models related with a polymorphic association. In order to do that, let’s create the two model objects:
You have to add the polymorphic option to the migration for the attachments before executing it.
Now that we have the two model objects, we install the nested_form gem files in our project:
So we are ready to create a carrierwave uploader:
and mount the uploader to the chosen field of the attachment model:
Pratically, a carrierwave uploader is a class that handles a certain type of uploading in your model. You just need to mount the uploader of a string field of your model. This is a very good design decision because it gives you a lot of flexibility, for example, when you want to share the same uploading features between two models.
Now, we are ready to add the nested feature to the article form. So let’s proceed in the following order:
You have to pay attention to the attr_accessible for attacchments_attributes. It won’t work if you don’t add that field to the list of accessible ones. And eventually we modify the form in the following way:
And we’re done!
I have created a demo app just in case you want to play with it a bit.