从邮件程序访问助手?

Sea*_*ara 49 ruby-on-rails ruby-on-rails-3

我试图从rails 3邮件程序访问帮助程序方法,以便访问当前用户的会话.

我把帮助器:应用程序放在我的邮件程序类中,这似乎有效,除了我的邮件程序无法使用其中定义的方法(我得到未定义的错误).有谁知道这应该如何工作?

这是我的班级:

class CommentMailer < ActionMailer::Base
  default :from => "Andre Fournier <andre@gfournier.com>"

  helper :application
end
Run Code Online (Sandbox Code Playgroud)

谢谢,肖恩

Wil*_*iss 70

要使您能够从ActionMailer视图访问应用程序帮助程序,请尝试添加以下内容:

add_template_helper(ApplicationHelper)
Run Code Online (Sandbox Code Playgroud)

到你的ActionMailer(就在你的default :from行下).

  • 对于rails 4+,你也可以做`helper ApplicationHelper` (3认同)

Jos*_*ter 51

使用 helper ApplicationHelper

class NotificationsMailer < ActionMailer::Base

  default from: "Community Point <Team@CommunityPoint.ca>"
  helper ApplicationHelper
  helper NotificationMailerHelper

  # ...other code...
Run Code Online (Sandbox Code Playgroud)

注意:这些辅助方法仅适用于视图.它们在邮件程序类中不可用(NotificationMailer在我的示例中).

如果您在实际的邮件程序类中需要它们,请使用include ApplicationHelper,如下所示:

class NotificationMailer < ActionMailer::Base

  include ApplicationHelper

  # ... the rest of your mailer class.

end
Run Code Online (Sandbox Code Playgroud)

另一个SO问题.

  • 重要的是要知道这些帮助器方法在邮件程序类中不可用(在我的示例中为"NotificationMailer"),但仅限于视图本身.如果你在邮件程序类中需要它们,你应该可以使用`include ApplicationHelper`. (13认同)

小智 25

这是一个非常古老的问题,但我没有看到完整的答案,所以我会尝试,因为我没有找到另一个资源.

这取决于您使用辅助模块中定义的方法执行的操作.如果它们是类方法,并且在特定实例上未调用的所有内容似乎都是3.2.13的类方法,则需要使用

extend ApplicationHelper
Run Code Online (Sandbox Code Playgroud)

如果是实例方法

include ApplicationHelper
Run Code Online (Sandbox Code Playgroud)

如果你想在邮件程序视图中使用它们

helper ApplicationHelper
Run Code Online (Sandbox Code Playgroud)


dan*_*ave 8

您可以尝试混合所需的帮助程序模块:

class CommentMailer < ActionMailer::Base
  include ApplicationHelper
end
Run Code Online (Sandbox Code Playgroud)

  • 我不确定这是否适用于观点.我猜不是.但是如果你想在邮件程序类本身中使用帮助程序,它肯定会有效. (2认同)

Sea*_*ara -4

实现我想要的目标的一种黑客方法是将我需要的对象(current_user.name + current_user.email)存储在线程属性中,如下所示Thread.current[:name] = current_user.name:然后在我的邮件程序中,我刚刚将新的实例变量分配给存储在线程中的那些值:@name = Thread.current[:name]。这可行,但如果使用延迟作业之类的东西,则不起作用。