Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid default scope overrides default value. Why?

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.

like image 621
Maxim Pontyushenko Avatar asked Oct 07 '15 14:10

Maxim Pontyushenko


1 Answers

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.

like image 198
ABrowne Avatar answered Sep 24 '22 06:09

ABrowne