ActiveRecord Validations for Models with has_many, belongs_to associations and STI

Posted by keruilin on Stack Overflow See other posts from Stack Overflow or by keruilin
Published on 2010-05-24T22:27:14Z Indexed on 2010/05/24 22:31 UTC
Read the original article Hit count: 229

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:

  1. 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.
  2. For BadgeB, how do I write a validation that it can only be awarded one time per game week?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about validation