【问题标题】:Issue with custom rake task in Rails 4Rails 4 中的自定义 rake 任务问题
【发布时间】:2017-01-05 01:02:25
【问题描述】:

我正在尝试创建一个 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

错误:

追踪:

【问题讨论】:

  • 你能显示一个错误,或者更详细地解释你的意思是“不工作”吗?
  • @maxple 我已经添加了错误。
  • 你的任务不是命名为listing_update_agent,这意味着你应该将它作为rake listings:listing_update_agent 来调用??? Listing_needs_update 是从哪里来的?如果您可以在列表上创建一个范围会更加清晰和高效,例如 Listing.not_updated_in_last_month 这样您就不必询问每个列表记录是否超过一个月。您直接处理需要处理的记录。
  • @DarioBarrionuevo 哇...我觉得自己很愚蠢。这是文件名......这是漫长的一天!您能否详细说明创建范围的建议?

标签: ruby-on-rails ruby rake rake-task


【解决方案1】:

我会在这里回答以使其更清楚。

你的任务被命名为listing_update_agent,这意味着你应该调用它:

rake listings:listing_update_agent

而不是:

rake listings:listing_needs_update

我还可以考虑对您的代码进行一些改进:

1) 任务做事,因此将您的任务称为 notify_outdated_listings

2) 获取需要通知的列表并仅处理这些列表会更有效,而不是像在任务中那样询问表中的每条记录。 您可以通过在列表模型中创建一个范围来实现这一点,例如:

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

您能说出这种变化可能带来的性能差异吗?

【讨论】:

  • 对不起,我在匆忙中弄乱了语法。现在检查答案。
  • 不用担心。我担心listing_agent_id 没有给我该代理的电子邮件地址。对此有何见解?
  • 不知道我是否理解,listing_agent_id 是一个关联字段,意味着一个Listing 属于一个ListingAgent?还是只是一个名为 listing_agent_id 的随机字段?
  • 有一个listing表和一个agent表。在listing表中有一个listing_agent_id列对应于agent表。
  • 所以它是一个关联字段。您不能以以下方式访问任务中的电子邮件:UpdateListingMailer.listing_update_agent(listing.listing_agent.email).deliver_now(或任何电子邮件列的名称)?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-07
  • 2014-08-10
  • 1970-01-01
相关资源
最近更新 更多