Carl Edwards
Carl Edwards

Reputation: 14474

Validating numeric uniqueness of two attributes in Rails

I have a model Track which has two attributes:

disc which represents what disc the track belongs to and number which represents the numeric order of the track on the album.

I'd like to validate the uniqueness of the track number to where there can only be one unique track number per disc. So for instance on Disc 1 (or Disc 2) there can only be one track with a track number of 1.

Is there a pre-existing way to do this in Rails' uniqueness validation where one attribute is dependent on another? If not what would be the best way to write the custom validation?

Upvotes: 1

Views: 147

Answers (1)

potashin
potashin

Reputation: 44601

You can try with validates_uniqueness_of with scope:

validates_uniqueness_of :number, scope: [:disc, album_id]

By the way, on the database level you should also validate it with unique index:

add_index :table_name , [:number, :disc, :album_id], unique: true

or use a gem providing a composite primary key feature.

Upvotes: 1

Related Questions