“undefined method” when calling helper method from controller in Rails

后端 未结 11 2059
傲寒
傲寒 2020-12-12 22:36

Does anyone know why I get

undefined method `my_method\' for #

when I call my_method(\"string\") from withi

11条回答
  •  暖寄归人
    2020-12-12 23:04

    though its not a good practice to call helpers in controller since helpers are meant to be used at views the best way to use the helpers in controller is to make a helper method in application_controller and call them to the controller,
    but even if it is required to call the helper in a controller
    then Just include the helper in the controller

    class ControllerName < ApplicationController
      include HelperName
      ...callback statements..
    

    and call the helper methods directly to the controller

     module OffersHelper
      def generate_qr_code(text)
        require 'barby'
        require 'barby/barcode'
        require 'barby/barcode/qr_code'
        require 'barby/outputter/png_outputter'
        barcode = Barby::QrCode.new(text, level: :q, size: 5)
        base64_output = Base64.encode64(barcode.to_png({ xdim: 5 }))
        "data:image/png;base64,#{base64_output}"
      end
    

    Controller

    class ControllerName < ApplicationController
    include OffersHelper
    
    def new
      generate_qr_code('Example Text')
    end
    end
    

    hope this helps !

提交回复
热议问题