mongoid 4.0.2
I have Test
class:
class Test
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Paranoia
field :successful, type: Boolean, default: false
default_scope ->{ where(successful: true) }
end
Then I do:
t=Test.new; t.successful
=> true
So here is the question: what is the reason behind this behaviour?
P.S. I have fixed it resetting successful
with the help of after_initialize
method.
Try calling Test.create(), successful will also be true. This seems strange, but think what you are saying in your default_scope... get all tests that are true.
This looks like something that came from active_record originally: rails3 default_scope, and default column value in migration however it is strictly followed active_record this should work, however it doesn't:
t= Test.unscoped.new; t.successful
=> true
In the mongo world, if you put on a default_scope it'll scope all objects with that and assume that you would want anything new to also have that same default. The work arounds are using callbacks. You mentioned hooking up the after_initialize which is a good choice, however you need to make sure you check whether it has actually been set. Another alternative would be to use a named scope rather than the default.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With