我想每晚午夜从桌子发送电子邮件,所以我创建了一个模型来跟踪要发送的所有通信.该Communication模型存储信件的来源,信息以及要作为html发送的信件的内容.用户输入一个标准以匹配该字母的意图:州,国家,喜欢的颜色等,它返回可接受的匹配列表.
迭代此可接受匹配列表,并为每个匹配生成新的通信.如何将部分视图的内容呈现为字符串以存储在数据库中以便在午夜传递.
@communication = Communication.new(params[:communication])
@communication.body = //Render Partial with local variables to string here
Run Code Online (Sandbox Code Playgroud)
2010年1月8日:我已经实现了中微子提出的解决方案,我的代码如下所示:
@communication.message_body = render_to_string(
:partial => "letters/small_letter",
:locals => { :quote => @quote})
Run Code Online (Sandbox Code Playgroud)
这种方法的缺点是它需要一个上下文,所以它必须在控制器中呈现,这排除了使用rake文件生成电子邮件.正如其他人指出的那样,使用通信模型的方法可能会引入一些不必要的复杂性.此时,由于我用于生成收件人列表的条件从未存储过,因此我选择继续使用通信模型.
ale*_*dev 39
至于(几乎)总是在Rails中,有一种方法: ActionController::Base#render_to_string
在Rails 3中,此方法被移至AbstractController::Rendering#render_to_string.
tad*_*man 11
您可能希望查看在控制器外部呈现模板的技术,例如:
http://geek.swombat.com/rails-rendering-templates-outside-of-a-contro
话虽这么说,最好使用内置的电子邮件发送类ActionMailer :: Base,它可以为您呈现模板.在通信模型中存储参数可能比存储展开的HTML更好,因为这些参数可以序列化,然后再推回到"send_X_notification"类型调用.
这些可以使用生成器构建:
script/generate mailer communications_mailer
Run Code Online (Sandbox Code Playgroud)
你可以试试这个(在rails控制台中):
class StaticRender < ActionController::Base
def self.render_erb(template_path, params)
view = ActionView::Base.new(ActionController::Base.view_paths, {})
class << view
include ApplicationHelper
end
view.render(:file => "#{template_path}.html.haml", :locals => params, :layout => false)
end
end
StaticRender.render_erb("home", {})
Run Code Online (Sandbox Code Playgroud)
你需要让视图"回家"....
| 归档时间: |
|
| 查看次数: |
20582 次 |
| 最近记录: |