@@ -1887,8 +1887,8 @@ in the default scope, the value in the default scope takes precedence:
1887
1887
Band.new # => #<Band _id: 5c3f74ddce4ef3791abbb088, name: nil, active: false>
1888
1888
1889
1889
Because a default scope initializes fields in new models as just described,
1890
- defining a default scope with a dotted key and a simple literal value is
1891
- not possible :
1890
+ defining a default scope with a dotted key and a simple literal value, while
1891
+ possible, is not recommended :
1892
1892
1893
1893
.. code-block:: ruby
1894
1894
@@ -1900,7 +1900,36 @@ not possible:
1900
1900
default_scope ->{ where('tags.foo' => 'bar') }
1901
1901
end
1902
1902
1903
- Band.create! # exception: BSON::String::IllegalKey ('tags.foo' is an illegal key in MongoDB. Keys may not start with '$' or contain a '.'.)
1903
+ Band.create!
1904
+ # => Created document: {"_id"=>BSON::ObjectId('632de48f3282a404bee1877b'), "tags.foo"=>"bar"}
1905
+ Band.create!(tags: { 'foo' => 'bar' })
1906
+ # => Created document: {"_id"=>BSON::ObjectId('632de4ad3282a404bee1877c'), "tags.foo"=>"bar", "tags"=>{"foo"=>"bar"}}
1907
+ Band.all.to_a
1908
+ # => [ #<Band _id: 632de4ad3282a404bee1877c, tags: {"foo"=>"bar"}> ]
1909
+
1910
+ Mongoid 8 allows dotted keys to be used in Mongoid, and when creating a document,
1911
+ the scope is added as a dotted key in the attributes:
1912
+
1913
+ .. code-block:: ruby
1914
+
1915
+ Band.new.attribute
1916
+ # => {"_id"=>BSON::ObjectId('632de97d3282a404bee1877d'), "tags.foo"=>"bar"}
1917
+
1918
+ Whereas when querying, Mongoid looks for an embedded document:
1919
+
1920
+ .. code-block:: ruby
1921
+
1922
+ Band.create!
1923
+ # => Created document: {"_id"=>BSON::ObjectId('632de48f3282a404bee1877b'), "tags.foo"=>"bar"}
1924
+ Band.where
1925
+ # => #<Mongoid::Criteria
1926
+ selector: {"tags.foo"=>"bar"}
1927
+ options: {}
1928
+ class: Band
1929
+ embedded: false>
1930
+ # This looks for something like: { tags: { "foo" => "bar" } }
1931
+ Band.count
1932
+ # => 0
1904
1933
1905
1934
A workaround is to define the default scope as a complex query:
1906
1935
@@ -1914,9 +1943,11 @@ A workaround is to define the default scope as a complex query:
1914
1943
default_scope ->{ where('tags.foo' => {'$eq' => 'bar'}) }
1915
1944
end
1916
1945
1917
- Band.create!(tags: {hello: 'world'})
1918
- Band.create!(tags: {foo: 'bar'})
1919
- Band.count # => 1
1946
+ Band.create!(tags: { hello: 'world' })
1947
+ Band.create!(tags: { foo: 'bar' })
1948
+ # does not add a "tags.foo" dotted attribute
1949
+ Band.count
1950
+ # => 1
1920
1951
1921
1952
You can tell Mongoid not to apply the default scope by using
1922
1953
``unscoped``, which can be inline or take a block.
0 commit comments