CarrierWave is the crown jewel for managing uploaded files in a Rails application, in this tutorial we will look at the process of uploading and processing images.
Now suppose we want to have an app where users can upload images and display them in a gallery.
The first thing we need to do is create a new rails project to which we will add image loading and processing functions, so launch a terminal window and run the following command:
$> rails new your_proyect_name
If you already have a created project you can skip this step.
Go to the project directory and open it in your favorite text editor, open Gemfile, go to the end of the file and add a carrier stone there.
Once you've added a gem to your Gemfile, go back to the terminal window and run the bundle command to install the gem.
Now let's create a scaffold resource to add carrierwave functionality, in your terminal window, run the following command:
$> rails g scaffold your_scaffold title:string description:text image:string
This command will create the necessary files and folders to work with us. When we have the scaffold resource, it's time to check it in our browser, in a terminal window run the following command.
$> rails s
To get the last prompt, open your browser and go to: localhost: 3000 If you don't get any errors, it's time to run our migrations to create the necessary tables in our database, so go back to the terminal window and run the following:
$> rake db:migrate
After migrating our database, we need to create a bootloader with the following command.
$> rails g uploader your_uploader
This command will create a folder in your application's directory called "downloaders" and inside that folder you'll find the bootloader class you created, open the bootloader in a text editor, and see that this file already has some code, and it comes with pretty good documentation on how you can configure it, but for the purposes of this tutorial we can leave it as it is. Now open your Image model to mount the bootloader:
|#This should go in your model|
|mount_uploader :image, YourUploaderClass|
Add this line under your attr_accessible call, and it should be all you need to add to your model to make the complete model code look like this.
|class Image < ActiveRecord::Base|
|attr_accessible :description, :image, :title|
|mount_uploader :image, ImagesUploader|
Navigate to the views folder and open the "new.html.erb" file created by the scaffold, edit the following line here and include the form to upload the files.
|<%= form_for(@image) do | f| %>|
Thus, the edited line should look like this: