ActiveRecord Validations for Models with has_many, belongs_to associations and STI
- by keruilin
I have four models:
User
Award
Badge
GameWeek
The associations are as follows:
User has many awards.
Award belongs to user.
Badge has many awards.
Award belongs to badge.
User has many game_weeks.
GameWeek belongs to user.
GameWeek has many awards.
Award belongs to game_week.
Thus, user_id, badge_id and game_week_id are foreign keys in awards table.
Badge implements an STI model. Let's just say it has the following subclasses: BadgeA and BadgeB.
Some rules to note:
The game_week_id fk can be nil for BadgeA, but can't be nil for BadgeB.
Here are my questions:
For BadgeA, how do I write a validation that it can only be awarded one time? That is, the user can't have more than one -- ever.
For BadgeB, how do I write a validation that it can only be awarded one time per game week?