我正在使用 mandrill-api(来自 MailChimp)在单个 API 调用中向许多人发送电子邮件。它需要一个 HTML 参数,我希望从 View 而不是直接在我无法访问 simple_format 的模型中生成该参数以应用于我保存在数据库中的纯文本 (self.body)。
示例代码:
class Request < ActiveRecord::Base
after_create :attempt_send
def attempt_send
require 'mandrill'
m = Mandrill::API.new
message = {
:subject=> "Subject",
:html => "#{self.body}"
}
sending = m.messages.send(message)
puts sending
end
end
这种情况让我对 MVC 感到头疼。我的应用程序的其余部分使用 Rails Action 邮件程序,因此电子邮件内容在 View 层中被干净地处理。
如果您能告诉我如何以某种方式使用 simple_format,那将是实现我在 self.body 上所需格式的快速修复。我对更优雅的解决方案持开放态度,以使此功能更像 Rails 邮件程序。我考虑过的一个选项是使用 Controller 方法返回电子邮件 html,但我认为这会导致自引用 http 请求,这不是一种有效的方法。开放的想法!
最佳答案
您可以包含模块 ActionView::Helpers::TextHelper
http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format
class Request < ActiveRecord::Base
include ActionView::Helpers::TextHelper
after_create :attempt_send
# ...
:html => "#{simple_format(self.body})"
--另一个不包括所有 TextHelper 方法的选项,只是您需要的一个选项是使用委托(delegate)。
delegate :simple_format, to: 'ActionController::Base.helpers'
关于ruby-on-rails - 如何使用 simple_format 或 View 在模型 after_create 回调中格式化 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16129789/