0

When I call

@certificate, @exp_date = certificate_with_date(@int, @coach)

in my email template view, I get the following error:

undefined method `certificate_with_date' for #<#<Class:0x0000564473b34af8>:0x0000564473b31ec0>

In my controller, I have included

helper_method :certificate_with_date

This is the method in question;

def certificate_with_date(num, coach)
    if num == 1
      return 'DBS', coach.DBS
    elsif num == 2
      return 'Safety', coach.safe_qual
    elsif num == 3
      return 'Coach', coach.coach_qual
    elsif num = 4
      return 'First Aid', coach.first_aid
    end
  end

N.B. I also call this method from another view and it works - for some reason in this particular view I get an error.

chumakoff
  • 6,807
  • 2
  • 23
  • 45
  • Please write path and name files to each of your part of the code, it will help understand where from and what you calling! Thank you! – Andriy Kondzolko Apr 25 '19 at 02:52
  • 1
    email template? you mean in an action mailer? in that case you need to put that method in the mailer as well. best, you put it into a helper and include that helper into the mailer https://stackoverflow.com/questions/1416978/how-to-use-my-view-helpers-in-my-actionmailer-views – phoet Apr 25 '19 at 07:01
  • @phoet Thank you! I thought that explicitly including the helper method in the controller would be enough to use in the ActionMailer view. I put that method into a helper and added add_template_helper to my mailer class and it worked :) – the_spiranian Apr 25 '19 at 11:11

1 Answers1

1

You should move your helper method into a separate module and then include the module into both the controller and the mailer using add_template_helper method. Then the helper methods will be available in controller and mailer views.

module SomeHelper
  def some_shared_method
    # ...
  end
end

class SomeController
  add_template_helper SomeHelper
end

class SomeMailer
  add_template_helper SomeHelper
end

Note: If you place the code into a helper module (in app/helpers directory) then you won't need to include the module into the controller as helper modules methods are available in controller views by default. However, you will still have to include the module into the mailer to make the method available in the mailer views.


If you also need to call the helper method in the controller, you can do it using the helpers method which gives you the access to helper methods.

class SomeController
  add_template_helper SomeHelper

  def some_method
    # ...
    # calling a helper method in controller 
    helpers.some_shared_method
    # ...
  end 
end

Or you can include the module into the controller using include method for the methods to be accessible in the controller directly.

class SomeController
  include SomeHelper

  def some_method
    # ...
    # calling the included method 
    some_shared_method
    # ...
  end 
end
chumakoff
  • 6,807
  • 2
  • 23
  • 45