the_spiranian
the_spiranian

Reputation: 65

Undefined method error when calling a helper method in controller from ActionMailer view

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.

Upvotes: 0

Views: 1188

Answers (1)

chumakoff
chumakoff

Reputation: 7034

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

Upvotes: 1

Related Questions