我想使用我在app/helpers/annotations_helper中定义的方法。rb在我的ReportMailer视图(app/views/report_mailer/usage_report.text.html.erb)。我怎么做呢?

根据本指南,似乎add_template_helper(helper_module)方法可以做我想做的事情,但我不知道如何使用它。

(顺便说一句,你在邮件视图中访问不同的一组助手有什么原因吗?这很烦人。)


当前回答

这就是我在rails 6中所做的

class ApplicationMailer < ActionMailer::Base
  default from: 'community@example.com'
  layout 'mailer'

  # Add whatever helper you want
  helper :application  

end

其他回答

在Rails4的例子中,我喜欢这样:

# app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
  add_template_helper ApplicationHelper
  ...
end

and

# app/mailers/user_mailer.rb
class AccountMailer < ApplicationMailer
  def some_method(x, y)
  end
end

这样您就不必在任何地方指定add_template_helper。

对于Rails 3中的所有邮件(设置"application" helper):

# config/application.rb:
...
config.to_prepare do
  ActionMailer::Base.helper "application"
end

你可以添加你的邮件

helper :application

或者任何你需要的帮手

在Rails 3中,只需使用ActionMailer类顶部的helper方法:

helper :mail   # loads app/helpers/mail_helper.rb & includes MailHelper

我只是传入了一个block,因为我只需要它在一个Mailer中:

helper do
  def host_url_for(url_path)
    root_url.chop + url_path
  end
end

(请确保设置config.action_mailer.default_url_options。)

(如果你使用url_for,一定要传入:only_path => false)

在您用于管理电子邮件的mailer类中:

class ReportMailer < ActionMailer::Base
  add_template_helper(AnnotationsHelper)

  ...
end