diff --git a/app/models/transcode.rb b/app/models/transcode.rb index 32afe201..835fc558 100644 --- a/app/models/transcode.rb +++ b/app/models/transcode.rb @@ -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 diff --git a/db/migrate/20231013145058_add_unique_index_on_format_and_track_to_transcode.rb b/db/migrate/20231013145058_add_unique_index_on_format_and_track_to_transcode.rb new file mode 100644 index 00000000..b8eba134 --- /dev/null +++ b/db/migrate/20231013145058_add_unique_index_on_format_and_track_to_transcode.rb @@ -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 diff --git a/db/schema.rb b/db/schema.rb index 96b069e4..0dc0d762 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[7.0].define(version: 2023_10_13_111950) do +ActiveRecord::Schema[7.0].define(version: 2023_10_13_145058) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -108,6 +108,7 @@ t.integer "format", default: 0, null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.index ["format", "track_id"], name: "index_transcodes_on_format_and_track_id", unique: true t.index ["track_id"], name: "index_transcodes_on_track_id" end diff --git a/test/models/transcode_test.rb b/test/models/transcode_test.rb index 7c8fa0bf..ceeaaeff 100644 --- a/test/models/transcode_test.rb +++ b/test/models/transcode_test.rb @@ -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