Skip to content

Commit

Permalink
Fix bug where the gem removes validation errors on relational fields
Browse files Browse the repository at this point in the history
  • Loading branch information
knovoselic committed Sep 26, 2016
1 parent fc2cff5 commit 67b35ec
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 8 deletions.
3 changes: 3 additions & 0 deletions .rspec
@@ -0,0 +1,3 @@
--color
--require spec_helper
--format documentation
5 changes: 3 additions & 2 deletions lib/mongoid-embedded-errors.rb
Expand Up @@ -16,9 +16,10 @@ def errors_with_embedded_errors
embedded_relations.each do |name, metadata|
# name is something like pages or sections
# if there is an 'is invalid' message for the relation then let's work it:
next unless errs[name]
next unless Array(public_send(name)).any?(&:invalid?)
# first delete the unless 'is invalid' error for the relation
errs.delete(name.to_sym)
errs[name].delete 'is invalid'
errs.delete name.to_sym if errs[name].empty?
# next, loop through each of the relations (pages, sections, etc...)
[send(name)].flatten.reject(&:nil?).each_with_index do |rel, i|
# get each of their individual message and add them to the parent's errors:
Expand Down
12 changes: 9 additions & 3 deletions spec/embedded_errors_spec.rb
@@ -1,8 +1,7 @@
require 'spec_helper'

describe Mongoid::EmbeddedErrors do
let(:article) { Article.new }
let(:invalid_page) { Page.new }
let(:valid_page) { Page.new title: 'test' }
let(:invalid_section) { Section.new }
let(:valid_section) { Section.new(header: 'My Header') }
let(:invalid_annotation) { Annotation.new }
Expand All @@ -24,6 +23,7 @@
end

it 'save works as before' do
article.pages << valid_page
article.save.should be_false
article.should_not be_persisted
article.errors.messages.should eql(
Expand All @@ -33,8 +33,14 @@
it 'handles errors on the main object' do
article.should_not be_valid
article.errors.messages.should eql(
name: ["can't be blank"], summary: ["can't be blank"]
name: ["can't be blank"],
summary: ["can't be blank"],
pages: ["can't be blank"]
)
end
it 'does not remove other validation errors from relational fields' do
article.validate
expect(article.errors[:pages]).to include "can't be blank"
end
end
end
7 changes: 4 additions & 3 deletions spec/support/models.rb
Expand Up @@ -3,14 +3,15 @@ class Article
include Mongoid::Timestamps
include Mongoid::EmbeddedErrors

embeds_many :pages
embeds_one :annotation

field :name, type: String
field :summary, type: String

validates :name, presence: true
validates :summary, presence: true

embeds_many :pages
embeds_one :annotation
validates :pages, presence: true
end

class Page
Expand Down

0 comments on commit 67b35ec

Please sign in to comment.