2017-01-05 38 views
0

我試圖創建一個Rake任務,當列表未在一個月內更新時,它將發送一封電子郵件,但似乎無法使其工作。Rails 4中的自定義Rake任務問題

我認爲這個問題可能是因爲我試圖提取listing_agent電子郵件,但我在那裏有listing_agent_id。

update_listing_mailer.rb:

class UpdateListingMailer < ActionMailer::Base 
    default from: "Help <[email protected]>" 

    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 

錯誤:

enter image description here

跟蹤:

enter image description here

+0

你能顯示一個錯誤,或更詳細地解釋你的意思是「不工作」嗎? –

+0

@maxple我添加了錯誤。 –

+0

是不是您的任務名爲listing_update_agent,這意味着您應該將其作爲rake列表調用它:listing_update_agent ??? listing_needs_update來自哪裏?如果你可以在Listing上創建一個範圍,比如Listing.not_updated_in_last_month,這將更加清晰和高效,所以如果它的歷史記錄大於一個月,你就不需要詢問每個列表記錄。您直接處理需要處理的記錄。 –

回答

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 

你能告訴在性能上的差異這種變化可以使 您可以像上市模型創建一個範圍實現這一目標?

+0

這不起作用。語法錯誤,但不知道什麼是正確的語法... –

+0

對不起,我搞砸了語法。現在檢查答案。 –

+0

不用擔心。我擔心listing_agent_id沒有讓我知道該代理的電子郵件地址。對此有何洞察? –

相關問題