Logic and Code Help

Here are my models and associations:

  • User has many rewards.
  • The premium belongs to the User.
  • The prize has many rewards.
  • Prize awarded

Suppose there are four Prizes (captured as entries):

  • Pony
  • A toy
  • Gum
  • Awesomestatus

Each day, the User can receive one or more of these Prizes. But the User can only receive every prize once a day. If the user wins AwesomeStatus, for example, the record is added to the reward table using fk for the user and bonus. Obviously, if the user does not win the AwesomeStatus in a day, the record is not added.

( , ), , AwesomeStatus. (, AwesomeStatus, .) , , , script. , , AwesomeStatus? : - . , ( ).

+3
3

, , - :

, , . , , :

# 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)

ARel - , , :)

+2

" " , (, , 5- , ).

, t-1, t:

SELECT prev.user_id 
FROM awards prev 
OUTER JOIN awards current ON prev.user_id = current.user_id 
AND prev.prize_id = current.prize_id 
AND current.time_period = 1000
WHERE prev.prize_id = 1 
AND current.prize_id IS NULL 
AND prev.time_period = 999
0

update_at _, , :

scope :awarded, proc {|date| where(["updated_at <= ?", date])}

. , :

awesome_status = Prize.find_by_name('AwesomeStatus')
p "Users who do not have AwesomeStatus anymore:"

User.all.each {|user| p user.username if user.awards.awarded(1.day.ago).collect(&:id).include?(awesome_status)}

, , - .., "lasts_for" cronjob , "" "" "false" .

0

Source: https://habr.com/ru/post/1794356/