Skip to content

Commit 2462477

Browse files
committed
Prevent duplicate file names within the same language scope.
1 parent e6157ea commit 2462477

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

app/validators/resource_language_validator.rb

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
class ResourceLanguageValidator < ActiveModel::Validator
22
def validate(record)
3+
return if record.file_name_override.blank?
4+
35
if TrainingResource.joins(:topic)
4-
.where(
5-
training_resources: { file_name_override: record.file_name_override },
6-
topics: { language_id: record.topic.language_id },
7-
)
8-
.any?
6+
.where(
7+
training_resources: { file_name_override: record.file_name_override },
8+
topics: { language_id: record.topic.language_id },
9+
).where.not(id: record.id)
10+
.any?
911
record.errors.add(:file_name_override, "This filename is already in use")
1012
end
1113
end
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,20 @@
11
require "rails_helper"
22

33
RSpec.describe TrainingResource, type: :model do
4+
subject { create(:training_resource) }
45
it { should validate_presence_of(:state) }
56
it { should have_one_attached(:document) }
7+
8+
it "should reject creation of resources with duplicated filenames within the same language" do
9+
resource = create(:training_resource, file_name_override: "filename.pdf")
10+
expect {
11+
create(:training_resource, file_name_override: "filename.pdf", topic_id: resource.topic_id)
12+
}.to raise_error(ActiveRecord::RecordInvalid)
13+
end
14+
15+
it "should allow creation of resources without file_name_override" do
16+
expect {
17+
create(:training_resource, file_name_override: nil)
18+
}.to change(TrainingResource, :count).by(1)
19+
end
620
end

0 commit comments

Comments
 (0)