我可能會做這樣的事情:
類獎也應該有一列awarded_at包含當天獎授予。所以,當現在是時候創建的獎項就可以這樣做:
# This will make sure that no award will be created if it already exists for the current date
@user.awards.find_or_create_by_prize_id_and_awarded_at(@prize.id, Time.now.strftime("%Y-%m-%d"))
,然後我們可以有一個範圍,以加載所有用戶提供了一個獎,將今日到期和所提供的獎金沒有活動的獎項。
# user.rb
scope :are_losing_award, lambda { |prize_id, expires_after|
joins("INNER JOIN awards AS expired_awards ON users.id = expired_awards.user_id AND expired_awards.awarded_at = '#{(Time.now - expires_after.days).strftime("%Y-%m-%d")}'
LEFT OUTER JOIN awards AS active_awards ON users.id = active_awards.user_id AND active_awards.awarded_at > '(Time.now - expires_after.days).strftime("%Y-%m-%d")}' AND active_awards.prize_id = #{prize_id}").
where("expired_awards.prize_id = ? AND active_awards.id IS NULL", prize_id)
}
然後我們可以這樣調用:
# Give me all users who got the prize three days ago and has not gotten it again since
User.are_losing_award(@prize.id, 3)
有可能是給阿雷爾查詢或更好的東西寫範圍的某些方面,我有沒有高手呢,但是這方式應工作到那麼:)
好問題.... – Andrew 2011-03-06 17:03:40