我无法让Rails立即向多个用户发送电子邮件。我正在尝试向与我们网站签名的多个场所发送通知,以便与其匹配的查询获得批准。
待定查询必须由管理员批准。邮件通过@enquiry
,即触发电子邮件时。在我的Enquiries controller
:
def approve
@enquiry.approve
redirect_to [:admin, @enquiry], notice: 'Enquiry is approved.'
SupplierMailer.new_enquiry(@enquiry).deliver
end
在我的Supplier_mailer.rb
中,我有这个方法:
def new_enquiry(enquiry)
@enquiry = enquiry
@enquiry.venues.each do |venue|
mail(to: venue.supplier.user.email, subject: 'You have a new enquiry')
end
end
目前,它只发送到1个电子邮件地址,因此无法正常循环。
型号:
Enquiry
has_and_belongs_to_many :venues
Supplier
has_many :venues
has_one :user
我做错了什么?
由于
答案 0 :(得分:9)
new_enquiry
方法应该构建一封电子邮件,然后使用deliver
方法发送。循环正常工作,但每次调用邮件时,都会覆盖其先前的调用,并且该方法返回最后一次调用。
相反,首先获取收件人列表,然后将其用作to
属性
emails = @enquiry.venues.map {|venue| venue.supplier.user.email}
mail(to: emails, subject: 'You have a new enquiry')
如果您不喜欢彼此发送其他电子邮件,则需要在循环中放置Mailer操作:
def approve
@enquiry.approve
redirect_to [:admin, @enquiry], notice: 'Enquiry is approved.'
@enquiry.venues.each do |venue|
SupplierMailer.new_enquiry(@enquiry, venue).deliver
end
end
def new_enquiry(enquiry, venue)
@enquiry = enquiry
mail(to: venue.supplier.user.email, subject: 'You have a new enquiry')
end
最终选项非常糟糕,但提供了最佳界面:
class SupplierMailer << ActionMailer::Base
def self.new_enquiry(enquiry)
@enquiry = enquiry
mails = @enquiry.venues.map do |venue|
mail(to: venue.supplier.user.email, subject: 'You have a new enquiry')
end
class << mails
def deliver
each(&:deliver)
end
end
mails
end