Ruby on Rails with carrierwave
File uploading in Ruby on Rails application with carrierwave gem using ImageKit.io.
This is a quick start guide to show you how to integrate ImageKit in the Ruby on rails application with carrierwave gem. The code samples covered here are hosted on Github - https://github.com/imagekit-samples/quickstart/tree/master/ruby/sample-app-with-carrierwave.
This guide walks you through the following topics:

Setting up ImageKit Ruby on Rails SDK

For this tutorial, we will create a fresh rails application and work with it. If you already have an existing Rails app, it is also possible to use that, although you would need to modify the terminal commands and configurations in this tutorial as applicable.
Let's create a new rails application. Create a new directory and enter the command:
1
rails new sample-app-with-carrierwave
Copied!
Now, navigate to the newly created directory, and run the app:
1
rails server
Copied!
In your web browser, navigate to http://localhost:3000/
You should see a generic welcome message (Yay! You're on Rails!).
Welcome message for a fresh Ruby on Rails application
Next, to use ImageKit functionality in our app, we will create a new controller with the following command:
1
rails generate controller Welcome
Copied!
This will generate a few scaffolding files for you. Go to config/routes.rb and add the following lines:
1
get 'welcome/index'
2
root 'welcome#index'
Copied!
Here, we are doing two things:
  1. 1.
    One, creating a route at the path _welcome/index, _to direct requests coming on that path to go to the index action of the Welcome controller, which we will add soon.
  2. 2.
    Second, we are declaring the root path to be directed to _welcome/index. _This means that all requests on http://localhost:3000/ will go to http://localhost:3000/welcome/index

Installing the SDK

First, add this line to your Gemfile to add the 'imagekitio' gem as a dependency.
1
gem 'imagekitio'
Copied!
Next, run the bundle install command to install the imagekitio gem from the RubyGems repository.
1
bundle install
Copied!

Initializing the SDK

Before the SDK can be used, let's learn about and configure the requisite authentication parameters that need to be provided to the SDK.
Create a file config/initializers/imagekitio.rb, open it and add your public and private API keys, as well as the URL Endpoint as follows: (You can find these keys in the Developer section of your ImageKit Dashboard)
1
ImageKitIo.configure do |config|
2
if Rails.env.development?
3
config.public_key = 'your_public_key'
4
config.private_key = 'your_private_key'
5
config.url_endpoint = 'your_url_endpoint' # https://ik.imagekit.io/your_imagekit_id
6
end
7
config.service = :carrierwave
8
# config.constants.MISSING_PRIVATE_KEY = 'custom error message'
9
end
Copied!
Restart the application
1
rails server
Copied!
The home screen will display an error message stating that the index action could not be found for the WelcomeController. Let's fix that. Open up the project in your text editor of choice, and navigate to app/controllers/welcome_controller.rb. Edit it to make it look like the following:
1
class WelcomeController < ApplicationController
2
def index
3
end
4
end
Copied!
and create app/views/welcome/index.html.erb file and edit file with text Hello world. Now refresh the browser it renders the Hello world.

Uploading images in Ruby on Rails application

There are two different methods of uploading a file to your ImageKit Media Library:
  1. 1.
    Direct image upload**.**
  2. 2.
    Attaching the image to a model using CarrierWave**.**

Direct image upload

First, add the following code to app/views/welcome/index.html.erb:
1
<h3>File Upload</h3>
2
<%= form_with(url: {action: :upload}, multipart: true) do %>
3
<%= file_field_tag 'picture' %>
4
<%= submit_tag "Upload" %>
5
<% end %>
6
7
<br>
8
9
<% flash.each do |name, msg| %>
10
<%= content_tag :div, msg, class: "alert alert-info" %>
11
<% end %>
Copied!
This creates a simple form with a file upload field and a submit button. The form submits the file to the path /welcome/upload. We need to add this path to our routes. Go to config/routes.rb, and add the following line:
1
post 'welcome/upload'
Copied!
Now, we have the route and the HTML markup set up to submit a file for uploading. Let's introduce the controller action 'welcome#upload' to receive the file and upload it to the Media Library. Go to app/controllers/welcome_controller.rb, and add the following method:
1
def upload
2
uploaded_file = params[:picture]
3
@imagekitio = ImageKitIo.client
4
output = @imagekitio.upload_file(
5
file: uploaded_file,
6
file_name: "new_file.jpg",
7
response_fields: 'tags',
8
tags: ["hello"]
9
)
10
if output[:error]
11
redirect_to "/", notice: "There was some problem uploading your image"
12
else
13
redirect_to "/", notice: "Your image has been uploaded successfully with the name of #{output[:response]["name"]}"
14
end
15
end
Copied!
Here, we first extract the file from the :picture property of the params object, and then upload the file to our Media Library by the name of new_file.jpg, using the upload_file() API. We also attach an example tag 'hello' to the image.
Now, refresh the home page, and you should see the upload field.
Upload field
Select an image/file from your local computer, and click on the Upload button. A success message shall flash below the file field.
Your image has been uploaded successfully with the name <NAME_OF_FILE>
Now, after upload, if you go to the Media Library section of your ImageKit dashboard, you should see the newly uploaded image.
If you get an authentication error during upload, verify that the API keys are configured correctly.
Fetching uploaded file
Fetch the uploaded image and display it in the UI by adding this line to your app/views/welcome/index.html.erb.
1
<%= image_tag "https://ik.imagekit.io/<YOUR_IMAGEKIT_ID>/<FILE_NAME>" %>
Copied!
The app should render your uploaded image correctly.

Attaching the image to a model (using CarrierWave)

You can attach an image as an attribute of one of your models, making it convenient to write a model-oriented code. This method uses the CarrierWave gem, which is a dependency of the imagekitio gem.
Open Gemfile and add carrierwave gem
1
gem 'carrierwave', '~> 2.0'
Copied!
run bundle install
Next, we'll create an entity called an uploader.
1
rails g uploader <Uploading_attribute_name>
2
# For example if you want to create uploader for Picture attribute then use
3
rails g uploader Picture
4
# Generated uploader's path will be app/uploaders/picture_uploader.rb
Copied!
Now, go to the generated uploader file - app/uploaders/<name>_uploader.eb, and enter the following code. The options configuration is optional.
1
class PictureUploader < CarrierWave::Uploader::Base
2
include ImageKitIo::CarrierWave
3
4
def options
5
options =
6
{
7
response_fields: 'isPrivateFile, tags',
8
tags: ["Rails SDK uploads"],
9
use_unique_file_name: false,
10
folder: "your_directory/"
11
}
12
end
13
14
# If you want to set upload dir then you can use following method or you can also use options method.
15
# This method shuld return string
16
def store_dir
17
"your_directory/"
18
end
19
20
end
Copied!
Now, we generate a model and give it a picture attribute, which will be an image. If you already have a model in your project, you can simply add the attribute to the existing model.
1
rails generate model Post
Copied!
Now go to the model file - app/models/post.rb, and add the following lines:
1
class Post < ApplicationRecord
2
attr_accessor :picture
3
mount_uploader :picture, PictureUploader
4
end
Copied!
You are free to change the name of the attribute from :picture to something else.
Perform the database migrations. This will add two columns - title, picture to the Posts table of our database.
1
rails g migration AddPictureToPosts picture:string
2
rails g migration AddTitleToPosts title:string
3
rails db:migrate
Copied!
Now, create another controller named after the model. For example, we'll create a controller called Post.
1
rails generate controller Posts
Copied!
Now, go to app/controllers/posts_controller.rb, and add the following methods:
1
class PostsController < ApplicationController
2
def index
3
@posts = Post.all
4
end
5
def show
6
@post = Post.find params[:id]
7
end
8
9
def new
10
@post = Post.new
11
end
12
13
def create
14
@post = Post.new post_params
15
if @post.save
16
redirect_to @post
17
else
18
render 'new'
19
end
20
end
21
22
def post_params
23
params.require(:post).permit(:title, :picture)
24
end
25
end
Copied!
Here, we create standard methods to show all posts, show a single post, and create a new post. These methods will have to be accompanied by some HTML markup as well. So go to app/views/posts/, and add the following files
index.html.erb
1
<%= @posts.each do |post| %>
2
<div class="post">
3
<div class="image">
4
<%= image_tag post.picture.url %>
5
</div>
6
<div class="content">
7
<%= link_to "#{post.title}", post_path(post), class: "header" %>
8
</div>
9
</div>
10
<% end %>
11
<%= link_to 'Back', posts_path %>
Copied!
new.html.erb
1
<%= form_with model: @post do |form| %>
2
3
<%= label_tag(:title, "Enter title of post") %>
4
<%= form.text_field :title %>
5
6
<%= label_tag(:picture, "Upload a picture") %>
7
<%= form.file_field :picture %>
8
9
<%= submit_tag "Submit" %>
10
<% end %>
11
12
<%= link_to 'Back', posts_path %>
Copied!
show.html.erb
1
<div class="post">
2
<div class="image">
3
<%= image_tag @post.picture.url %>
4
</div>
5
<div class="content">
6
<%= link_to "#{@post.title}", post_path(@post), class: "header" %>
7
</div>
8
</div>
9
<%= link_to 'Back', posts_path %>
Copied!
And finally let's add the routes config/routes.rb
1
resources :posts
Copied!
Now, restart the server and go to _http://localhost:3000/posts/new. _You should see two form fields, for title, and picture. Enter a text value for the title field, and upload an image/file for the picture field, and click on Submit. This should redirect you to _http://localhost:3000/posts/1, _displaying the title and the image.
This sums up how you can upload images to your Media Library using the SDK. The second method is more suited for RESTful applications with CRUD operations where the image is an attribute of a resource.

Authentication parameter generation

You can use the SDK to generate authentication parameters that are required if you want to implement client-side upload functionality using javascript or some front-end framework.
1
# app/controllers/welcome_controller.rb
2
3
def auth_params
4
@imagekitio = ImageKitIo.client
5
@auth_params = @imagekitio.get_authentication_parameters()
6
end
Copied!
1
# config/routes.rb
2
3
get 'welcome/auth_params'
Copied!
1
# app/views/welcome/auth_params.html.erb
2
3
<div>
4
<%= @auth_params %>
5
</div>
Copied!
The get_authentication_parameters(token = nil, expire = nil) takes two optional arguments, token, and expire. token defaults to a random string if not provided. expire defaults to infinite.
You should see an output like this:
1
{
2
:token=>"6b4d79e5-eb36-4de0-8ef5-534c88e45ebf",
3
:expire=>1600957501,
4
:signature=>"4c19c4066a140921eddaff7aaa3625df2bf8182a"
5
}
Copied!

What's next

The possibilities for image manipulation and optimization with ImageKit are endless. Learn more about it here: