| name | constraints-reviewer |
| description | Review data constraints and referential integrity in Rails models and migrations. |
| allowed-tools | Read Grep Glob Bash |
Constraints & Referential Integrity Review
Review database constraints, foreign keys, and data integrity rules.
Database-Level Enforcement
validates :email, uniqueness: true
add_index :users, :email, unique: true
validates :email, uniqueness: true
Race Condition Prevention
def claim_slot
return false if Slot.where(user_id: user.id).exists?
Slot.create!(user_id: user.id)
end
def claim_slot
Slot.create!(user_id: user.id)
rescue ActiveRecord::RecordNotUnique
false
end
Missing Constraints Checklist
| Validation | Required DB Constraint |
|---|
presence: true | NOT NULL |
uniqueness: true | Unique index |
belongs_to | Foreign key |
enum | Check constraint |
numericality: { in: } | Check constraint |
Foreign Key Cascades
has_many :comments
has_many :comments, dependent: :destroy
add_foreign_key :comments, :posts, on_delete: :cascade
Polymorphic Associations
belongs_to :commentable, polymorphic: true
ALLOWED_TYPES = %w[Post Article].freeze
validates :commentable_type, inclusion: { in: ALLOWED_TYPES }
belongs_to :post, optional: true
belongs_to :article, optional: true
validates :post_id, presence: true, unless: :article_id?
Orphan Detection Queries
Comment.left_joins(:post).where(posts: { id: nil })
ActiveRecord::Base.connection.tables.each do |table|
columns = ActiveRecord::Base.connection.columns(table)
columns.select { |c| c.name.end_with?('_id') }.each do |col|
end
end
Review Checklist
Output Format
## Constraints Review: [PASS/WARN/FAIL]
### Missing Database Constraints
- [model]: [validation without DB enforcement]
### Foreign Key Issues
- [table]: [missing FK on _id column]
### Race Condition Risks
- [code location]: [check-then-insert pattern]
### Orphan Risks
- [association]: [could create orphans]
### Recommendations
1. [Prioritized fixes]