我正在尝试创建一个Rake任务,该任务会在一个月内未更新商家信息时发送电子邮件,但似乎无法使其发挥作用。
我认为问题可能是我试图提取listing_agent电子邮件,但我在那里有listing_agent_id。
update_listing_mailer.rb:
class UpdateListingMailer < ActionMailer::Base
default from: "Help <help@realestate.com>"
def listing_update_agent(agent)
@agent = agent
@listing = listing
mail to: "#{agent.email}", subject: "Your listing hasn't been updated in a month!"
end
end
listing_update_agent.html.erb:
Hiya, <br><br>
The listings below have not been updated in a month! Is it still on the market? If so, please update. If not, please remove from the market.<br><br>
<strong>Address:</strong> <%= @listing.address %>
<strong>Last Updated:</strong> <%= @listing.updated_at %>
<br><br>
Thanks,<br>
Management
listing_needs_update.rake:
namespace :listings do
desc "Sends an email to the listing agent when that listing hasn't been updated in a month"
task listing_update_agent: :enviroment do
Listing.all.each do |listing|
if listing.updated_at == Date.today - 30
UpdateListingMailer.listing_update_agent(listing.listing_agent_id).deliver_now
end
end
end
end
错误:
迹:
答案 0 :(得分:1)
我会在这里回答更清楚。
您的任务名为listing_update_agent,这意味着您应该将其命名为:
rake listings:listing_update_agent
而不是:
rake listings:listing_needs_update
我还可以考虑对代码进行一些改进:
1)任务执行任务,因此将您的任务称为 notify_outdated_listings
更具语义性2)获取需要通知的列表并且仅使用那些列表更有效率,而不是像在执行任务时那样询问表中的每条记录。 您可以通过在Listing模型中创建一个范围来实现这一点,如:
class Listing < ActiveRecord::Base
scope :not_updated_in_last_month, -> { where('updated_at >= ?', 1.month.ago) }
end
然后在你的任务中:
namespace :listings do
desc "Sends an email to the listing agent when that listing hasn't been updated in a month"
task listing_update_agent: :enviroment do
Listing.not_updated_in_last_month.each do |listing|
UpdateListingMailer.listing_update_agent(listing.listing_agent_id).deliver_now
end
end
end
你能说出这种变化可能带来的性能差异吗?