Skip to content

Commit

Permalink
Merge pull request #121 from ohbarye/enable-attached-validator-message
Browse files Browse the repository at this point in the history
Enable to set message on error of attached validator
  • Loading branch information
igorkasyanchuk authored Jun 8, 2021
2 parents 5b2beae + ade4950 commit 0dbeede
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 4 deletions.
5 changes: 4 additions & 1 deletion lib/active_storage_validations/attached_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ class AttachedValidator < ActiveModel::EachValidator # :nodoc:
def validate_each(record, attribute, _value)
return if record.send(attribute).attached?

record.errors.add(attribute, :blank)
errors_options = {}
errors_options[:message] = options[:message] if options[:message].present?

record.errors.add(attribute, :blank, **errors_options)
end
end
end
4 changes: 2 additions & 2 deletions test/active_storage_validations_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class ActiveStorageValidations::Test < ActiveSupport::TestCase
test 'validates presence' do
u = User.new(name: 'John Smith')
assert !u.valid?
assert_equal u.errors.full_messages, ["Avatar can't be blank", "Photos can't be blank"]
assert_equal u.errors.full_messages, ["Avatar must not be blank", "Photos can't be blank"]

u = User.new(name: 'John Smith')
u.avatar.attach(dummy_file)
Expand All @@ -24,7 +24,7 @@ class ActiveStorageValidations::Test < ActiveSupport::TestCase
u = User.new(name: 'John Smith')
u.photos.attach(dummy_file)
assert !u.valid?
assert_equal u.errors.full_messages, ["Avatar can't be blank"]
assert_equal u.errors.full_messages, ["Avatar must not be blank"]
end

test 'validates content type' do
Expand Down
2 changes: 1 addition & 1 deletion test/dummy/app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class User < ApplicationRecord

validates :name, presence: true

validates :avatar, attached: true, content_type: :png
validates :avatar, attached: { message: "must not be blank" }, content_type: :png
validates :photos, attached: true, content_type: ['image/png', 'image/jpg', /\A.*\/pdf\z/]
validates :image_regex, content_type: /\Aimage\/.*\z/
validates :conditional_image, attached: true, if: -> { name == 'Foo' }
Expand Down

0 comments on commit 0dbeede

Please sign in to comment.