# CarrierWave Cheatsheet The CarrierWave gem provides us with an easy way to allow file uploads through forms. ## Installation In your Gemfile, include ```ruby gem 'carrierwave' ``` and then `bundle install`. ## Getting Started ### Add a column to store the file's URL You need to have a column of type "string" in whichever table that you want to attach a file upload to. This column will, ultimately, store the URL of the uploaded file after CarrierWave hosts it. If you already included the column when you generated your resource, great. Skip to the next step. If not, you have to add it. For example, here we add a column called "avatar" to users, which we plan to store an image in: ```bash rails generate migration add_avatar_to_users avatar:string rake db:migrate ``` In your case, it may be song, transcript, image, etc. ### Generate an uploader From the command line: ```bash rails generate uploader Avatar ``` In your case, change "Avatar" to match whatever you are trying to upload / the column you added to the table: Song, Transcript, Image, etc. **Restart your `rails server`.** ### Mount the uploader in the model In the relevant model, ```ruby # app/models/user.rb class User < ActiveRecord::Base mount_uploader :avatar, AvatarUploader end ``` Again, customize to match your use case. `:avatar` should be the column you created, and `AvatarUploader` should be whatever you generated. ### Enhance the form We need an `` in our form to handle the upload. If you already have a `type="text"` input, change it; or if you don't, add a new one: ```erb ``` > If you are customizing a Devise form, it would instead look like `<%= f.file_field :avatar, :class => "form-control" %>`. We also need to change the `
` tag itself to allow files to be uploaded by adding the `enctype="multipart/form-data"` attribute: ```erb ``` > If you are customizing a Devise form, it would instead look like `<%= form_for(resource, as: resource_name, url: registration_path(resource_name), :html => { :multipart => true }) do |f| %>`. ## Assign the file just like any other params In your create/update actions, assign the new file upload just like any other form parameter: ```ruby @user.avatar = params[:avatar] ``` > If you are customizing a Devise form, you'll have to instead [allow this additional parameter through security](https://gist.github.com/rbetina/9ef4a9ffa4604df74bb5#step-three-allow-additional-parameters-through-security). That should be it! ## Retrieving the upload CarrierWave will, by default, process the upload and then store it in your `public` folder, so that you can use it just like any other URL on the internet. For example, we could now do ```erb ``` ## Further Reading - [Official docs](https://github.com/carrierwaveuploader/carrierwave) - [Railscast #253](http://railscasts.com/episodes/253-carrierwave-file-uploads)