Rails rails 中的 mail 视图里怎么调用自定义的 helper?

baypm2014 · 2014年12月23日 · 最后由 saiga 回复于 2014年12月23日 · 2823 次阅读

问题是这样的: rails:4.0 我在邮件视图中需要调用 application_helper.rb 中的一个函数 (current_user),但总是发送失败,感觉问题就在于邮件视图中无法调用自定义的 helper。

application_helper.rb:

module ApplicationHelper
  def current_user
    begin
      @current_user ||= User.find_by_token!(cookies[:user]) if cookies[:user]
      @current_user ||= User.find_by_token!(session[:user]) if session[:user]
    rescue ActiveRecord::RecordNotFound
      @current_user = nil
      logger.info("====== warning: different pc login ======")
    end
    @current_user
  end

邮件视图比如:

<p><%= current_user.name%></p>

但就是报错啊报错,我在 Mailer 中 include 什么都不行。

class UserMailer < ActionMailer::Base
  #add_template_helper(ApplicationHelper)
  #helper ApplicationHelper

也都尝试过也不行。

各位有遇到这种情况吗?

  1. 你应该把错误信息发上来。
  2. 即使引入了 Helper,Mailer 环境是没有 cookies 和 session 的。

#1 楼 @Rei 刚测了一下,还真是 cookies 和 session 的问题。感谢提示。

#1 楼 @Rei 有什么方法可以解决 mailer 环境有 cookies 的问题吗? 由于邮件内容是复用之前的页面,里边有太多的地方用到<%= current_user ....%>,如果通过 controller 传给 mailer 里,@current_user=current_user,再在 view 里将原先的 current_user 全修改或从写为@current_user,这样的代价太大了,会导致之前的页面挂掉。有没有解决方法可以使 mailer 环境包含 cookies 的方式。

#3 楼 @baypm2014 Mailer 需要的变量都用参数传进去。

#3 楼 @baypm2014 不要复用针对网页浏览的模板。邮件客户端对 HTML 的支持程度是不同的,直接用网页模板很可能样式错误。

论元编程的错误用法....

# controller.rb
def create
  accessor = instance_variable_get(:@_request)
  UserMailer.send :define_method, 'session', -> { accessor.session }
end

个人推荐四楼的做法,当参数传进去吧

需要 登录 后方可回复, 如果你还没有账号请 注册新账号