如下所示,我有一个非常简单的类,它有两个验证行,第二个需要被注释掉才能让 find_by 工作。第二行的性质似乎没有什么区别。似乎是一个错误。(请注意,我想在 Mongoid 邮件列表上发布此问题,但被告知它不接受新成员。)
gem 'rails', '3.2.11'
gem "mongoid", "~> 3.0.0"
uhoh.rb
============================================================
class Uhoh < Object
include Mongoid::Document
field :f1, type: String
field :f2, type: String
validates :f1, presence: true
validates :f2, presence: false ##### Get error below if this line NOT commented out
end
uhoh_test.rb
============================================================
require 'test_helper'
class TestUhoh < ActiveSupport::TestCase
def test_1
Mongoid.purge!
Uhoh.create(f1: 'a')
self.assert_nothing_raised(Exception){Uhoh.find_by(f1: 'a')}
end
end
Test result, with line NOT commented out
============================================================
C:\Ruby193\bin\ruby.exe -e
$stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) -Itest
C:/Users/PJD/RubymineProjects/Metronome/test/unit/uhoh_test.rb
Testing started at 7:25 PM ...
Rack::File headers parameter replaces cache_control after Rack 1.5.
Run options:
# Running tests:
E
Finished tests in 0.045003s, 22.2207 tests/s, 22.2207 assertions/s.
1) Error:
test_1(TestUhoh):
Mongoid::Errors::DocumentNotFound:
Problem:
Document not found for class Uhoh with attributes {:f1=>"a"}.
Summary:
When calling Uhoh.find_by with a hash of attributes, all attributes
provided must match a document in the database or this error will be
raised.
Resolution:
Search for attributes that are in the database or set the
Mongoid.raise_not_found_error configuration option to false, which
will cause a nil to be returned instead of raising this error.
C:/Ruby193/lib/ruby/gems/1.9.1/gems/mongoid-3.0.21/lib/mongoid/finders.rb:96:in `find_by'
C:/Users/PJD/RubymineProjects/Metronome/test/unit/uhoh_test.rb:6:in `block in test_1'
1 tests, 1 assertions, 0 failures, 1 errors, 0 skips
Process finished with exit code 1
Test result, with line YES commented out
============================================================
C:\Ruby193\bin\ruby.exe -e
$stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) -Itest
C:/Users/PJD/RubymineProjects/Metronome/test/unit/uhoh_test.rb
Testing started at 7:26 PM ...
Rack::File headers parameter replaces cache_control after Rack 1.5.
Run options:
# Running tests:
.
Finished tests in 0.039003s, 25.6391 tests/s, 25.6391 assertions/s.
1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
Process finished with exit code 0