**Scenario**

I have Media than can have many audio Tracks, I want to store the sequence of the tracks within the media, but for a particular media the sequence has to be unique. So for example a Media object may have 10 tracks, each having a sequence of 1, 2, .. 10

```
class Medium < ActiveRecord::Base
  has_many   :tracks, inverse_of: :medium, dependent: :destroy
end

class Track < ActiveRecord::Base
  belongs_to :medium

  validates_uniqueness_of :sequence, scope: :medium, message: 'sequence is not unique for the medium'
end

```

However, a user can change the sequence of tracks, for example they move the second track to the 8th position - this will result in the sequence for the tracks with sequence 3 - 8 being decremented by one (becoming 2 - 7 respectively) and the original track with sequence 2 becoming track 8. 

**Problem**

The issue is I can't simply change the values and save the tracks because of course the validation fails.

The only solution I can think of is to:

1. set the first effected track with a temporary but unique sequence number and save it.
2. decrement the sequence number for other tracks and save them.
3. reassign the first track with its correct sequence number and save that.

However, this seems to be very inefficient, and only caters for this one scenario. I could be moving a track the other way, from position 8 to position 2, for example.

Ideally I want to allow the user to change the sequences on tracks and modify other data and, only once happy, submit which will result in a call to an action that will invoke `media.save`.

Is there a better practice in Rails for handling this scenario or is it as complex as it seems. Is it better practice to treat this as a special case and handle each change to sequence atomically - meaning hit the server as soon as the user changes a track sequence (other track attribute changes being handled by the parent save being called, i.e.. `media.save`)