Skip to content

Commit eb7161f

Browse files
removed validation only on change for non-persisted docs
1 parent 3cefc7d commit eb7161f

File tree

2 files changed

+61
-1
lines changed

2 files changed

+61
-1
lines changed

lib/mongoid/validatable/associated.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def validate_association(document, attribute)
7474
# use map.all? instead of just all?, because all? will do short-circuit
7575
# evaluation and terminate on the first failed validation.
7676
list.map do |value|
77-
if value && !value.flagged_for_destroy? && (!value.persisted? || value.changed?)
77+
if value && !value.flagged_for_destroy?
7878
value.validated? ? true : value.valid?
7979
else
8080
true

spec/mongoid/association_spec.rb

+60
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,66 @@ class AssocationSpecModel
115115
expect(name).to_not be_an_embedded_many
116116
end
117117
end
118+
119+
context "validation tests on associated values" do
120+
before(:all) do
121+
class Author
122+
include Mongoid::Document
123+
embeds_many :books, cascade_callbacks: true
124+
field :condition, type: Boolean
125+
end
126+
127+
class Book
128+
include Mongoid::Document
129+
embedded_in :author
130+
validate :parent_condition_is_not_true
131+
132+
def parent_condition_is_not_true
133+
return unless author&.condition
134+
errors.add :base, "Author condition is true."
135+
end
136+
end
137+
138+
Author.delete_all
139+
Book.delete_all
140+
end
141+
142+
let(:author) { Author.new }
143+
let(:book) { Book.new }
144+
145+
context "when author is not persisted" do
146+
it "is valid without books" do
147+
expect(author.valid?).to be true
148+
end
149+
150+
it "is valid with a book" do
151+
author.books << book
152+
expect(author.valid?).to be true
153+
end
154+
155+
it "is not valid when condition is true with a book" do
156+
author.condition = true
157+
author.books << book
158+
expect(author.valid?).to be false
159+
end
160+
end
161+
162+
context "when author is persisted" do
163+
before do
164+
author.books << book
165+
author.save
166+
end
167+
168+
it "remains valid initially" do
169+
expect(author.valid?).to be true
170+
end
171+
172+
it "becomes invalid when condition is set to true" do
173+
author.update_attributes(condition: true)
174+
expect(author.valid?).to be false
175+
end
176+
end
177+
end
118178
end
119179

120180
describe "#embedded_one?" do

0 commit comments

Comments
 (0)