Skip to content

Commit

Permalink
Merge pull request #1038 from pod4lib/1025-conditional-model-validation
Browse files Browse the repository at this point in the history
Change upload validation to avoid input error on form
  • Loading branch information
corylown authored Mar 13, 2024
2 parents 6f74e0f + bc54277 commit c26b31d
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
6 changes: 5 additions & 1 deletion app/models/upload.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class Upload < ApplicationRecord
has_many :marc_profiles, dependent: :delete_all
belongs_to :user, optional: true
belongs_to :allowlisted_jwts, optional: true
validates :url, presence: true, if: proc { |upload| upload.files.blank? }
validate :url_presence_if_no_uploaded_files
validates :files, presence: true, if: proc { |upload| upload.url.blank? }
validate :valid_url, if: proc { |upload| upload.url.present? }
scope :active, -> { where(status: %w[active processed]) }
Expand Down Expand Up @@ -68,6 +68,10 @@ def read_marc_record_metadata(**options, &block)

private

def url_presence_if_no_uploaded_files
errors.add(:url, 'A URL must be provided if a file has not been uploaded') if !files.attached? && url.blank?
end

def perform_extract_marc_record_metadata_job
ExtractMarcRecordMetadataJob.perform_later(self)
end
Expand Down
3 changes: 2 additions & 1 deletion spec/models/upload_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
it 'validates that a URL or files are present' do
expect do
create(:upload, files: [])
end.to raise_error(ActiveRecord::RecordInvalid, "Validation failed: Url can't be blank, Files can't be blank")
end.to raise_error(ActiveRecord::RecordInvalid,
"Validation failed: Url A URL must be provided if a file has not been uploaded, Files can't be blank")
end

context 'with an invalid URL' do
Expand Down

0 comments on commit c26b31d

Please sign in to comment.