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

MONGOID-5822: Embedded association validations break when association depends on parent update #5922

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
2 changes: 1 addition & 1 deletion lib/mongoid/validatable/associated.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def validate_association(document, attribute)
# use map.all? instead of just all?, because all? will do short-circuit
# evaluation and terminate on the first failed validation.
list.map do |value|
if value && !value.flagged_for_destroy? && (!value.persisted? || value.changed?)
if value && !value.flagged_for_destroy?
value.validated? ? true : value.valid?
else
true
Expand Down
60 changes: 60 additions & 0 deletions spec/mongoid/association_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,66 @@ class AssocationSpecModel
expect(name).to_not be_an_embedded_many
end
end

context "when validation depends on association" do
before(:all) do
class Author
include Mongoid::Document
embeds_many :books, cascade_callbacks: true
field :condition, type: Boolean
end

class Book
include Mongoid::Document
embedded_in :author
validate :parent_condition_is_not_true

def parent_condition_is_not_true
return unless author&.condition
errors.add :base, "Author condition is true."
end
end

Author.delete_all
Book.delete_all
end

let(:author) { Author.new }
let(:book) { Book.new }

context "when author is not persisted" do
it "is valid without books" do
expect(author.valid?).to be true
end

it "is valid with a book" do
author.books << book
expect(author.valid?).to be true
end

it "is not valid when condition is true with a book" do
author.condition = true
author.books << book
expect(author.valid?).to be false
end
end

context "when author is persisted" do
before do
author.books << book
author.save
end

it "remains valid initially" do
expect(author.valid?).to be true
end

it "becomes invalid when condition is set to true" do
author.update_attributes(condition: true)
expect(author.valid?).to be false
end
end
end
end

describe "#embedded_one?" do
Expand Down
Loading