Rails:电子邮件“deliver_”方法的自定义模板?

时间:2010-06-16 15:16:03

标签: ruby-on-rails email

我正在构建一个电子邮件系统,将我的不同电子邮件存储在数据库中,并通过method_missing调用相应的“deliver_”方法(因为我无法显式声明方法,因为它们是用户生成的)。

我的问题是我的rails应用程序仍会尝试为生成的电子邮件呈现模板,尽管这些模板不存在。我想强制所有电子邮件使用相同的模板(views/test_email.html.haml),这些模板将被设置为从我的数据库记录中绘制其格式。

我怎样才能做到这一点?我尝试在render :template => 'test_email'中的test_email方法中添加emailer_controller但没有运气。


models/emailer.rb

class Emailer < ActionMailer::Base

  def method_missing(method, *args)
    # not been implemented yet
    logger.info "method missing was called!!"
  end

end

controller/emailer_controller.rb

class EmailerController < ApplicationController

  def test_email
    @email = Email.find(params[:id])
    Emailer.send("deliver_#{@email.name}")
  end

end

views/emails/index.html.haml

%h1 Listing emails
%table{ :cellspacing => 0 }
  %tr
    %th Name
    %th Subject
  - @emails.each do |email| 
    %tr
      %td=h email.name
      %td=h email.subject
      %td= link_to 'Show', email
      %td= link_to 'Edit', edit_email_path(email)
      %td= link_to 'Send Test Message', :controller => 'emailer', :action => 'test_email', :params => { :id => email.id }
      %td= link_to 'Destroy', email, :confirm => 'Are you sure?', :method => :delete
%p= link_to 'New email', new_email_path

我遇到上述错误:

  

缺少模板

     

缺少模板   emailer / name_of_email_in_database.erb在视图中   路径应用/视图

3 个答案:

答案 0 :(得分:0)

尝试多部分可能有效

  def test_email
    @email = Email.find(params[:id])
    Emailer.send("deliver_#{@email.name}")
    part :content_type => 'multipart/alternative' do |copy|
      copy.part :content_type => 'text/plain' do |plain|
        plain.body = render( :file => "conta.text.plain.erb",  :email=>@email )
      end
      copy.part :content_type => 'text/html' do |html|
        html.body = render( :file => "conta.text.html.erb",  :email => @email )
      end
    end
  end

答案 1 :(得分:0)

Aph,我觉得很傻。我弄清楚了:

models/emailer.rb

class Emailer < ActionMailer::Base

  def method_missing(method, *args)
    logger.info "method missing was called!!"
    recipients  "Test <test@test.com>" 
    body        "#{ Email.find_by_name(method.to_s).body }"
  end

end

由于传入的method基本上是记录的名称,我可以直接提取存储在数据库中的正文内容,并将其作为电子邮件正文传递,完全绕过模板。

答案 2 :(得分:0)

我会“升级”

换句话说,对每个人的电子邮件使用相同的视图。但在视图中,根据user_id呈现不同的文本。

请记住,视图可以调用render方法。

就我而言,我让用户使用液体模板系统上传电子邮件模板。 (Google for rails liquid templates。)使用液体是好的,因为它是安全的 - 用户不能在他们的模板中包含任意ruby代码。

然后我的电子邮件视图呈现液体模板,从而生成自定义的电子邮件。