Generate a QR Code Server Side with Ruby on Rails

I went to a meetup to find out how to generate a QR Code Server side with Ruby on Rails. There was a guy called Dan that helped me figure this out, so this publication is dedicated to that man.

Ever thought about throwing a mini-festival? Been inspired by how low the bar has been set by Fyre festival? If you have answered yes to either of these questions, then you’re more than likely to be interested in making money and selling tickets. One way to verify that someone has purchased a ticket is via a QR Code.

I started in the usual way (badly):

  • create a rails app,
  • create a model called “ticket” with a code parameter that took a string.
  • Setup a Ticket controller with “show” method
  • Setup my routes with resources :tickets, only: :show
  • Go into Rails controller and create a ticket [Ticket.create(code: “123”)]. I check rails controller and see I’ve generated a ticket correctly.
  • I install the “rqrcode gem” from this library

Since this is a simple Rails app for now and I like to pretend I know something about media assets, I decide that an SVG is the perfect media format to use. The following shows my Ticket Controller:

My show view only has <%= @svg %> and hey presto! I get something:

Not quite what I was expecting. But Dan let me know there’s a quick way to fix it! By adding a single method of html_safe to @svg in the view (<%= @svg.html_safe %>), I was able to generate a qr code that looked like a qr code!

Awesome!

Now, how about generating a unique QRCode for each purchaser? Super simple when you now how (Dan knew). On the model, we must generate a random code and save it to the Ticket object from within our Ticket model.

Then adapt our controller so that the randomly generated QRCode takes the SecureRandom generated hex as the argument:

NOICE!!!