Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

has_(one/many)_attached presence validation #31956

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions activestorage/lib/active_storage/attached/one.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ def attachment
record.public_send("#{name}_attachment")
end

def blank?
attachment.blank?
end

# Associates a given attachment with the current record, saving it to the database.
#
# person.avatar.attach(params[:avatar]) # ActionDispatch::Http::UploadedFile object
Expand Down
30 changes: 30 additions & 0 deletions activestorage/test/models/presence_validation_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# frozen_string_literal: true

require "test_helper"
require "database/setup"

class ActiveStorage::PresenceValidationTest < ActiveSupport::TestCase
class Admin < User; end

teardown do
Admin.clear_validators!
end

test "validates_presence_of has_one_attached" do
Admin.validates_presence_of :avatar
a = Admin.new
assert_predicate a, :invalid?

a.avatar.attach create_blob(filename: "funky.jpg")
assert_predicate a, :valid?
end

test "validates_presence_of has_many_attached" do
Admin.validates_presence_of :highlights
a = Admin.new
assert_predicate a, :invalid?

a.highlights.attach create_blob(filename: "funky.jpg")
assert_predicate a, :valid?
end
end