我可能会做这样的事情:
类奖也应该有一列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