我的應用程序涉及人們進入主頁,輸入他們爲了好玩而打賭的名字,他們的電子郵件地址,他們想要提醒的日期以及一些關於賭注的細節。我每天都用這個運行一次的寶石。在用戶選擇的日期發送電子郵件
bet.rb
class Bet < ActiveRecord::Base
attr_accessible :details, :email, :name, :reminder, :sent
# Sends user a reminder if current_date is equal to the reminder date of the bet
def check_bet
current_date = Time.now.strftime("%Y-%m-%d").to_s
@bets = Bet.all
@bets.each do |bet|
BetMailer.bet_reminder(bet).deliver and bet.sent = true and bet.save! if bet.reminder.to_s == current_date
end
end
end
schedule.rb
every :day, :at => '5:00pm' do
runner "Bet.check_bet"
end
bet_mailer.rb
class BetMailer < ActionMailer::Base
default from: "[email protected]"
def bet_reminder(bet)
@bet = bet
mail to: bet.email, subject: bet.name + " Reminder"
end
end
我已經成功的我n當current_date等於他們想要提醒的日期(提醒)時發送電子郵件。爲了測試這一點,我已經進入軌道控制檯,選擇一個特定的投注對象,並使用跑check_bet方法就可以了:在終端完成上述
1.9.2p320 :013 > Bet.last.check_bet
Bet Load (2.8ms) SELECT "bets".* FROM "bets" ORDER BY "bets"."id" DESC LIMIT 1
Bet Load (0.9ms) SELECT "bets".* FROM "bets"
(0.2ms) BEGIN
(0.3ms) COMMIT
(0.2ms) BEGIN
(0.3ms) COMMIT
(0.2ms) BEGIN
(0.2ms) COMMIT
=> [#<Bet id: 3, name: "Newsroom", email: "[email protected]", reminder: "2013-07-30", details: "Mac and Will are going to get back together.", sent: false, created_at: "2013-07-29 17:23:13", updated_at: "2013-07-29 17:23:13">, #<Bet id: 4, name: "Testing", email: "[email protected]", reminder: "2013-07-29", details: "This is a test", sent: true, created_at: "2013-07-29 18:38:42", updated_at: "2013-07-29 20:17:34">, #<Bet id: 5, name: "Cheaper iPhone", email: "[email protected]", reminder: "2013-07-29", details: "I bet Dad that there will be a cheaper iphone in th...", sent: true, created_at: "2013-07-29 20:39:33", updated_at: "2013-07-29 20:50:14">, #<Bet id: 6, name: "My grades", email: "[email protected]", reminder: "2013-07-29", details: "My grades this year will be > 84% average", sent: true, created_at: "2013-07-29 20:56:18", updated_at: "2013-07-29 21:14:21">]
後,我的郵箱是滿所有具有提醒=當前日期的投注對象。這證明SMTP設置正在工作,並且我的視圖中的代碼工作正常。
然而,當我嘗試對所有輸入對象的運行check_bet方法,我收到一個未定義的方法錯誤:
1.9.2p320 :016 > Bet.all.check_bet
Bet Load (1.8ms) SELECT "bets".* FROM "bets"
NoMethodError: undefined method `check_bet' for #<Array:0x007ffdd2c8c6c0>
from (irb):16
from /Users/bvlaar/.rvm/gems/[email protected]/gems/railties-3.2.13/lib/rails/commands/console.rb:47:in `start'
from /Users/bvlaar/.rvm/gems/[email protected]/gems/railties-3.2.13/lib/rails/commands/console.rb:8:in `start'
from /Users/bvlaar/.rvm/gems/[email protected]/gems/railties-3.2.13/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>
「
此外,當我跑了」捆綁EXEC時'在終端的命令,似乎沒有發送。
請分享您在控制檯中使用的代碼,以「對所有投注對象運行check_bet方法」。另外,你收到的錯誤信息是否真的以'#<>結尾?還是你在'<>'之間留下了什麼? –
@PeterAlfvin我會將其添加到我的文章。不,我只是認爲散列無關緊要。謝謝 – Questifer
'#<>'是Ruby的對象符號,在這種情況下特別相關,因爲它會告訴你有關發送'check_bet'方法的對象。 –