Ruby on Rails
Saturday, July 9, 2016
You could model the problem by having a User model + many associated Point models. Point would store the number of points awarded + created_at (+ other data if needed). Spending points would result in creating a Point model with a negative number of awarded points.
1. Computing the total number of points of a user:
user.points.where('number > 0').sum(:number)
or with a scope:
user.points.awarded.sum(:number)
2. Computing the total number of spendable points:
user.points.awarded.where('created_at > ?', 2.months.ago).sum(:number)
Again, the where part can be expressed as a scope:
user.points.awarded.spendable.sum(:number)
3. Spending points would require a check against currently spendable points:
if points_to_spend <= user.points.awarded.spendable.sum(:number)
user.points.create!(number: -points_to_spend)
else
fail("not enough points")
end
You may also define methods like User#total_awarded_points, User#spendable_points and User#spend_points.
Would this work for you?
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/CAA6WWt-98pFxNJdhU9STKGKRNZ-RjTxr9ySbOCFSV4WVNfpYqA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment