Skip to content

Commit

Permalink
Provide a better error message on :required association
Browse files Browse the repository at this point in the history
Fixes #18696.
  • Loading branch information
nygrenh committed Jan 28, 2015
1 parent 71a8420 commit 9a6c6c6
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 3 deletions.
5 changes: 5 additions & 0 deletions activemodel/CHANGELOG.md
@@ -1,3 +1,8 @@
* Change the default error message from `can't be blank` to `must exist` for
the presence validator of the `:required` option on `belongs_to`/`has_one` associations.

*Henrik Nygren*

* Assigning an unknown attribute key to an `ActiveModel` instance during initialization
will now raise `ActiveModel::AttributeAssignment::UnknownAttributeError` instead of
`NoMethodError`
Expand Down
1 change: 1 addition & 0 deletions activemodel/lib/active_model/locale/en.yml
Expand Up @@ -14,6 +14,7 @@ en:
empty: "can't be empty"
blank: "can't be blank"
present: "must be blank"
required: "must exist"
too_long:
one: "is too long (maximum is 1 character)"
other: "is too long (maximum is %{count} characters)"
Expand Down
Expand Up @@ -31,7 +31,7 @@ def create_#{name}!(*args, &block)
def self.define_validations(model, reflection)
super
if reflection.options[:required]
model.validates_presence_of reflection.name
model.validates_presence_of reflection.name, message: :required
end
end
end
Expand Down
24 changes: 22 additions & 2 deletions activerecord/test/cases/associations/required_test.rb
Expand Up @@ -40,7 +40,7 @@ class Child < ActiveRecord::Base

record = model.new
assert_not record.save
assert_equal ["Parent can't be blank"], record.errors.full_messages
assert_equal ["Parent must exist"], record.errors.full_messages

record.parent = Parent.new
assert record.save
Expand All @@ -64,12 +64,32 @@ class Child < ActiveRecord::Base

record = model.new
assert_not record.save
assert_equal ["Child can't be blank"], record.errors.full_messages
assert_equal ["Child must exist"], record.errors.full_messages

record.child = Child.new
assert record.save
end

test "required has_one associations have a correct error message" do
model = subclass_of(Parent) do
has_one :child, required: true, inverse_of: false,
class_name: "RequiredAssociationsTest::Child"
end

record = model.create
assert_equal ["Child must exist"], record.errors.full_messages
end

test "required belongs_to associations have a correct error message" do
model = subclass_of(Child) do
belongs_to :parent, required: true, inverse_of: false,
class_name: "RequiredAssociationsTest::Parent"
end

record = model.create
assert_equal ["Parent must exist"], record.errors.full_messages
end

private

def subclass_of(klass, &block)
Expand Down

0 comments on commit 9a6c6c6

Please sign in to comment.