使用actiomailer重用几个电子邮件方法的相同视图

时间:2013-03-26 18:19:46

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2 actionmailer

class AdminMailer < ActionMailer::Base
  def send_message_to_user(user, subject, body, locale)
    @body = body
    mail(:to => user.email, :subject => subject)
  end

  def send_message_to_all_users(user, subject, body, locale)
    @body = body
    mail(:to => user.email, :subject => subject)
  end

  def send_message_to_active_users(user, subject, body, locale)
    @body = body
    mail(:to => user.email, :subject => subject)
  end

  def send_message_to_suspended_users(user, subject, body, locale)
    @body = body
    mail(:to => user.email, :subject => subject)
  end
end

我想为每个操作使用4个视图send_message_to_active_users.html.erbsend_message_to_all_users.html.erbsend_message_to_suspended_users.html.erbsend_message_to_user.html.erb,我只想为所有操作使用1个视图文件动作。

我该怎么做?

谢谢!

2 个答案:

答案 0 :(得分:1)

要选择其他模板,您可以将:template_name作为选项传递:

mail(:to => user.email, :subject => subject, :template_name => "another_template_name")

因此,您可以将一个模板用于多种方法。

答案 1 :(得分:0)

回复是:

class AdminMailer < ActionMailer::Base
  def send_message_to_user(user, subject, body, locale)
    @body = body
    mail(:to => user.email, :subject => subject) do |format|
      format.html { render "send_email_to_users" }
    end
  end

  def send_message_to_all_users(user, subject, body, locale)
    @body = body
    mail(:to => user.email, :subject => subject) do |format|
      format.html { render "send_email_to_users" }
    end
  end

  def send_message_to_active_users(user, subject, body, locale)
    @body = body
    mail(:to => user.email, :subject => subject) do |format|
      format.html { render "send_email_to_users" }
    end
  end

  def send_message_to_suspended_users(user, subject, body, locale)
    @body = body
    mail(:to => user.email, :subject => subject) do |format|
      format.html { render "send_email_to_users" }
    end
  end
end

您可以查看http://api.rubyonrails.org/classes/ActionMailer/Base.html

谢谢!