Skip to content

Commit

Permalink
Ensure that only one transcode of each format exists for each track
Browse files Browse the repository at this point in the history
Adding this uniqueness constraint will allow us to be a bit less
defensive in the code that looks up transcodes.
  • Loading branch information
chrislo committed Oct 13, 2023
1 parent 39ab930 commit b44a839
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 1 deletion.
2 changes: 2 additions & 0 deletions app/models/transcode.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,6 @@ class Transcode < ApplicationRecord
belongs_to :track
enum format: { mp3v0: 0 }
has_one_attached :file

validates :format, presence: true, uniqueness: { scope: [:track_id] }
end
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# frozen_string_literal: true

class AddUniqueIndexOnFormatAndTrackToTranscode < ActiveRecord::Migration[7.0]
def change
add_index :transcodes, %i[format track_id], unique: true
end
end
3 changes: 2 additions & 1 deletion db/schema.rb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions test/models/transcode_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,18 @@ class TranscodeTest < ActiveSupport::TestCase
test 'fixture is valid' do
assert build(:transcode).valid?
end

test 'validates only one of each format exists for each track' do
track = create(:track)
different_track = create(:track)
create(:transcode, format: :mp3v0, track:)

duplicate_transcode = build(:transcode, format: :mp3v0, track:)

assert_not duplicate_transcode.valid?

different_track_transcode = build(:transcode, format: :mp3v0, track: different_track)

assert different_track_transcode.valid?
end
end

0 comments on commit b44a839

Please sign in to comment.