How to store QR codes in rails generated from rqrcode

2.7k Views Asked by At

I need to generate a QR code and store it in rails. I am using rqrcode gem for generating QR code.

Here is how I am generating QR code as png.

  def generate_qr_code(checkin_url)
    qrcode = RQRCode::QRCode.new(checkin_url)
    png = qrcode.as_png(
      bit_depth: 1,
      border_modules: 4,
      color_mode: ChunkyPNG::COLOR_GRAYSCALE,
      color: 'black',
      file: nil,
      fill: 'white',
      module_px_size: 6,
      resize_exactly_to: false,
      resize_gte_to: false,
      size: 120
    )
    self.update!(qr_code_image: png.to_s)
  end

Issue: I am facing issues while storing the QR code in qr_code_image.

self.update!(qr_code_image: png.to_s) showing following error:

*** NoMethodError Exception: undefined method `map' for #<String:0x007feb358121d0>
Did you mean?  tap

Even IO.write("/tmp/github-qrcode.png", png.to_s) showing

*** Encoding::UndefinedConversionError Exception: "\x89" from ASCII-8BIT to UTF-8

I finally have to store the png image in qr_code_image where I am using

mount_uploaders :qr_code_image, QrCodeUploader
1

There are 1 best solutions below

4
On

Method png.to_s return a binary content of file

To write a file from a binary contente run:

File.binwrite("/tmp/github-qrcode.png", png.to_s)

If you want save a png.to_s on your database, I think that use a base64 is a good choice.

To save a base64 in your model the code is something like that

u = User.find(1)
u.qr_code_image = Base64.encode64(png.to_s)
u.save

Finaly, to see a qrcode in browser just

<img src="data:image/png;base64,<%= user.qr_code_image %>" />