Skip to content

Commit 2746d4c

Browse files
MONGOID-5822: Embedded association validations break when association depends on parent update (#5922) (#5924)
1 parent c3a9ac9 commit 2746d4c

File tree

2 files changed

+61
-1
lines changed

2 files changed

+61
-1
lines changed

lib/mongoid/validatable/associated.rb

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

spec/mongoid/association_spec.rb

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,66 @@
100100
expect(name).to_not be_an_embedded_many
101101
end
102102
end
103+
104+
context "when validation depends on association" do
105+
before(:all) do
106+
class Author
107+
include Mongoid::Document
108+
embeds_many :books, cascade_callbacks: true
109+
field :condition, type: Boolean
110+
end
111+
112+
class Book
113+
include Mongoid::Document
114+
embedded_in :author
115+
validate :parent_condition_is_not_true
116+
117+
def parent_condition_is_not_true
118+
return unless author&.condition
119+
errors.add :base, "Author condition is true."
120+
end
121+
end
122+
123+
Author.delete_all
124+
Book.delete_all
125+
end
126+
127+
let(:author) { Author.new }
128+
let(:book) { Book.new }
129+
130+
context "when author is not persisted" do
131+
it "is valid without books" do
132+
expect(author.valid?).to be true
133+
end
134+
135+
it "is valid with a book" do
136+
author.books << book
137+
expect(author.valid?).to be true
138+
end
139+
140+
it "is not valid when condition is true with a book" do
141+
author.condition = true
142+
author.books << book
143+
expect(author.valid?).to be false
144+
end
145+
end
146+
147+
context "when author is persisted" do
148+
before do
149+
author.books << book
150+
author.save
151+
end
152+
153+
it "remains valid initially" do
154+
expect(author.valid?).to be true
155+
end
156+
157+
it "becomes invalid when condition is set to true" do
158+
author.update_attributes(condition: true)
159+
expect(author.valid?).to be false
160+
end
161+
end
162+
end
103163
end
104164

105165
describe "#embedded_one?" do

0 commit comments

Comments
 (0)