The default mongoid region overrides the default value. What for?

mongoid 4.0.2

I have a 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, the question is: what is the reason for this behavior?

PS I set it to reset successful using the after_initialize method.

+6
source share
1 answer

Try calling Test.create (), a success will also be true. This seems odd, but think what you say in your default_scope ... get all the tests that are true.

This is similar to what was originally from active_record: rails3 default_scope and the default column value during migration , however, active_record is strictly enforced, this should work, t:

 t= Test.unscoped.new; t.successful => true 

In the world of mongo, if you put default_scope, it will cover all objects with this and assume that you want something new to have the same defaults too. Work around uses callbacks. You mentioned the after_initialize connection, which is a good choice, however you need to make sure that you check if it was actually installed. Another alternative would be to use a named scope rather than the default.

+1
source

All Articles