frcake
frcake

Reputation: 258

RoR STI Single of each type for every parent model instance

Im trying to validate the count of models that inherit from Parent model and keep them unique.

So i have

User has_many :parents
Parent belongs_to :user

Also I'm using single table inheritance for this , so:

rails g model Type1Parent --parent=Parent

overall i have 3 types , so Type1Parent,Type2Parent,Type3Parent.

Every user must have only one of each type, so for example

type1parent = user.type1parents.new
type1parent.save #=> OK!

but if i try do this again

type1parent = user.type1parents.new 
type1parent.save #=> Error: User already has a type1parents

but also be able to create a type2parent for the same user.

So , how can i validate the single existence of each type for every user?

Upvotes: 0

Views: 180

Answers (1)

Alfie
Alfie

Reputation: 2784

Add this scoped uniqueness validation to your Parent model:

validates :type, uniqueness: { scope: :user_id }

Also as suggested by @MrYoshiji add a unique index on type, user_id on the parents table

Upvotes: 1

Related Questions