将Rails视图呈现为电子邮件字符串
收藏

I'd like to send emails from a table every night at midnight, so I've created a model to track all communications to be sent. This Communication model stores who the letter is to, from, and the contents of the letter to be sent as html. The user enters a criteria to match for whom the letter is intended: state, country, favorite color, and so which returns a list of acceptable matches.

遍历此可接受的匹配列表,并为每个列表生成新的通信。如何将部分视图的内容呈现为字符串以存储在数据库中以在午夜交付。

@communication = Communication.new(params[:communication])
@communication.body = //Render Partial with local variables to string here

2010年1月8日:我已经实现了neutrino提出的解决方案,我的代码如下所示:

@communication.message_body = render_to_string(
  :partial => "letters/small_letter", 
  :locals => { :quote => @quote})

这种方法的缺点是它需要上下文,因此必须在控制器中呈现它,这排除了使用rake文件生成电子邮件的可能性。正如其他人指出的那样,使用通信模型的方法可能会引入一些不必要的复杂性。此时,由于从未存储用于生成收件人列表的条件,因此我选择继续使用通信模型。

最佳答案

As (almost) always in Rails, there's a method for that: ActionController::Base#render_to_string

In Rails 3, this method was moved to AbstractController::Rendering#render_to_string.

    公众号
    关注公众号订阅更多技术干货!