ruby on rails - Logic and code help -


here models , associations:

  • user has many awards
  • award belongs user
  • prize has many awards
  • award belongs prize

let's pretend there 4 prizes (captured records):

  • pony
  • toy
  • gum
  • awesomestatus

every day user can awarded 1 or more of these prizes. user can receive each prize once per day. if user wins awesomestatus, ex, record added awards table fk user , prize. obviously, if user doesn't win awesomestatus day, no record added.

at end of day (before midnight, let's say), want return list of users lost awesomestatus. (of course, lose awesomestatus, had have day before.) unfortunately, in case, don't think observers work , have rely on script. regardless, how go determining users lost awesomestatus? note: don't make solution overly dependent on period of time -- in case day. want maintain flexibility in how many times per whatever period users have opportunity win prize (and lose it).

i this:

the class award should have column awarded_at contains day prize awarded. when time create award can done this:

# make sure no award created if exists current date @user.awards.find_or_create_by_prize_id_and_awarded_at(@prize.id, time.now.strftime("%y-%m-%d")) 

and can have scope load users award expire today , no active awards supplied prize.

# user.rb scope :are_losing_award, lambda { |prize_id, expires_after|    joins("inner join awards expired_awards on users.id = expired_awards.user_id , expired_awards.awarded_at = '#{(time.now - expires_after.days).strftime("%y-%m-%d")}'          left outer join awards active_awards on users.id = active_awards.user_id , active_awards.awarded_at > '(time.now - expires_after.days).strftime("%y-%m-%d")}' , active_awards.prize_id = #{prize_id}").   where("expired_awards.prize_id = ? , active_awards.id null", prize_id) } 

so can call this:

# give me users got prize 3 days ago , has not gotten again since user.are_losing_award(@prize.id, 3) 

there might ways write scope better arel queries or something, i'm no expert yet, way should work until :)


Comments

Popular posts from this blog

Javascript line number mapping -

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -