validation - Validating numeric uniqueness of two attributes in Rails -
i have model track
has 2 attributes:
disc
represents disc track belongs , number
represents numeric order of track on album.
i'd validate uniqueness of track number there can 1 unique track number per disc. instance on disc 1 (or disc 2) there can 1 track track number
of 1.
is there pre-existing way in rails' uniqueness validation 1 attribute dependent on another? if not best way write custom validation?
you can try validates_uniqueness_of
scope
:
validates_uniqueness_of :number, scope: [:disc, album_id]
by way, on database level should validate unique index
:
add_index :table_name , [:number, :disc, :album_id], unique: true
or use gem providing composite primary key feature.
Comments
Post a Comment