【发布时间】:2012-02-22 04:17:50
【问题描述】:
这完全是一个新手问题,但我想知道是否有人可以协助设置邮件程序。我有一个模型“用户”并在其下方嵌套了一个“联系人”模型(具有 has_many/belongs_to 关系)。
我现在正在尝试创建一个邮件程序,该邮件程序将由用户页面上的特定操作(创建帖子)触发,并将通过电子邮件发送属于该用户的所有联系人。但我无法破解邮件所需的语法——我尝试将收件人设置为@user.contacts.all,并尝试像使用this solution 一样遍历它们。任何人都可以建议最干净的方法吗?
这是我目前的代码:
Posts controller:
after_create :send_contact_email
private
def send_contact_email
ContactMailer.contact_email(self).deliver
end
contact_mailer(这是我最近的尝试,取自 RoR 网站 - 我怀疑这不是最好的方法......)
class ContactMailer < ActionMailer::Base
def contact_email(user)
recipients @user.contacts.all
from "My Awesome Site Notifications <notifications@example.com>"
subject "Welcome to My Awesome Site"
sent_on Time.now
body {}
end
end
然后是contact_email.html.erb的基本消息。
当前错误是:
UsersController#create_post 中的 NoMethodError
nil:NilClass 的未定义方法 `contacts'。
您能提供的任何建议都将非常感激!
* 更新 *
按照 Baldrick 的建议,contact_email 方法现在是:
class ContactMailer < ActionMailer::Base
default :to => Contact.all.map(&:contact_email),
:from => "notification@example.com"
def contact_email(user)
@user = user
mail(:subject => "Post added")
end
end
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3.1 actionmailer