Generating a QR code and overlaying it in another image file in Rails

So recently I was given the task of creating a Ticketing system for a music festival and I had to create a system in which I would be able to generate a list of tickets ( which is basically a predesigned JPG image with an area which has been left out for the QR code which will be added dynamically )

So to do this, I used the help of RQRCode gem and Carrierwave Gem. Here is my Gemfile, just adding the ones that I used for the task:

gem 'rqrcode'
gem "mini_magick"
gem 'carrierwave', '~> 1.0'
gem 'carrierwave-base64'
gem 'simple_form'

My task here was simple, I had to create a model which would create the list of tickets, so aptly I named my model ticket.rb

Here is my code for the ticket Model:

# == Schema Information
# Table name: tickets
# id :bigint(8) not null, primary key
# random_code :string(255)
# user_listed :string(255)
# qr_code :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# ticket_type :integer
# number_of_tickets :integer
# student :integer

class Ticket < ApplicationRecord

# So that all the values that get generated is random
validates :random_code, uniqueness: true

validates :user_listed, presence: true

mount_base64_uploader :qr_code, QrCodeUploader
after_create :update_generate_code

def update_generate_code
base_64_image =
size: 300
self.qr_code = base_64_image!


I needed to somehow use imagemagick to composite the QR code that has been generated into the designed Image file. So in the uploaded for the QRCode that I created with Carrierwave, I simply added this code :

def maketicket
second_image ='http://localhost:3000/ticket.jpg')
manipulate! do |img|
second_image.composite(img) do |c|
c.compose "Over" # OverCompositeOp
# c.gravity "Northeast" # copy second_image onto first_image from (20, 20)
c.geometry "+2100+130"


process :maketicket

So everytime now my model was created, I was also creating the ticket which I can then show in my view files.

Leave a Reply

Your email address will not be published. Required fields are marked *