我有一个 Rails 应用程序,当满足某些条件时,我想向用户发送通知。我可以通过 rake 任务来做到这一点。目前,我能够选择符合条件的记录并将它们通过电子邮件发送到特定地址。问题是它发送所有帐户的所有记录。这是我在 rake 任务中的内容:
task :send_reminds => :environment do
equipment = Equipment.where("calibration_date <= ?", Date.today)
EquipmentMailer.out_of_calibration(equipment).deliver
end
这是我的 EquipmentMailer 的代码:
class EquipmentMailer < ActionMailer::Base
default :from => "mark.odonnell@azzurgroup.com"
def out_of_calibration(equipment)
@equipment = Equipment.where("calibration_date <= ?", Date.today)
mail(:to => "markaodonnell@gmail.com", :subject => "Equipment is out of calibration")
end
end
这是我的 HTML 电子邮件的代码(按预期工作):
The following Equipment is Due:
<br></br>
<table>
<tr>
<th>Equipment Name</th>
<th> </th>
<th>Calibration Due Date</th>
</tr>
<% @equipment.each do |equipment| %>
<tr>
<td><%= equipment.equipment_id %></td>
<td> </td>
<td><%= equipment.calibration_date %></td>
</tr>
<% end %>
</table>
如您所见,我将电子邮件直接发送给自己,并收到符合条件的设备列表。但这当然是不可接受的。我希望将电子邮件发送给帐户中具有未校准设备的所有用户。这是我的模型:
设备.rb
class Equipment < ActiveRecord::Base
acts_as_tenant(:account)
validates :equipment_id, presence: true
validates :location, presence: true
validates_uniqueness_to_tenant :serial_number
has_many :assets, :dependent => :destroy
accepts_nested_attributes_for :assets, :allow_destroy => true
has_paper_trail
def self.text_search(query)
if query.present?
search(query)
else
scoped
end
end
用户.rb
class User < ActiveRecord::Base
acts_as_tenant(:account)
validates_uniqueness_to_tenant :email
attr_accessible :name, :email, :password, :password_confirmation, :title, :company,
:phone, :mobile, :admin
has_secure_password
before_save :create_remember_token
belongs_to :account
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX }
validates :password, length: { minimum: 6 }
validates :password_confirmation, presence: true
# has_paper_trail
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end
账户.rb
class Account < ActiveRecord::Base
attr_accessible :subdomain, :email
VALID_SUBDOMAIN_REGEX = /\A[\w+\-.]+(-[a-z\d])+(-[a-z\d])/i
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :subdomain, :presence => true,
:uniqueness => true
validates :email, :presence => true,
format: { with: VALID_EMAIL_REGEX }
validates_presence_of :plan_id
belongs_to :plan
has_many :users
has_many :equipment, :through => :users
before_save { |account| account.subdomain = account.subdomain.downcase }
end
我已经为 mail(:to => user.email) 而不是直接地址尝试了类似的方法,同时将设备列表限制为特定于帐户及其用户。
@equipment = Equipment.where("calibration_date <= ?", Date.today)
@equipment.each do |equipment|
equipment.accounts.each do |account|
accounts.users.each do |user|
user.email.each do |email|
mail(:to => email, :subject => "Equipment is out of calibration"
end
end
end
end
rake 任务将毫无错误地运行,但我没有收到任何电子邮件。想法?顺便说一句,我只有大约 1 个月的时间入轨,所以如果我遗漏了一些非常基本的东西,你将不得不原谅我。