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

Setting up ImageKit Ruby on Rails SDK

We will create a new rails application for this tutorial and work with it.
If you already have an existing Rails app, 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-activestorage
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 = :active_storage
8
# config.constants.MISSING_PRIVATE_KEY = 'custom error message'
9
end
10
#make sure to replace the your_public_key, your_private_key and your_url_endpoint with actual values
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

Attaching the image to a model (using active_storage)

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 ActiveStorage gem, which is a dependency of the imagekitio gem. Note: From Rails version 5, rails support active_storage by default.
1
rails active_storage:install
2
rails db:migrate
Copied!
Let's add imagekit service on config/storage.yml as below:
1
imagekitio:
2
service: ImageKitIo
Copied!
and on config/environments/development.rb file:
1
config.active_storage.service = :imagekitio
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
has_one_attached :picture
3
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 AddTitleToPosts title:string
2
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(transformation: [{height: 200, width: 300}]) %>
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: