origin icon indicating copy to clipboard operation
origin copied to clipboard

reorder() inside scopes

Open johnnyshields opened this issue 11 years ago • 2 comments

reorder without arguments is ignored inside scopes when there is a default scope. However, with arguments will work as expected. In order words, there seems to be no way to clear a sort entirely from within a scope lambda expression. For example:

class MyDoc
  include Mongoid::Document

  default_scope ->{ asc(:foo, :bar) }

  scope :scope_1 ->{ where(foo: "hello").reorder }
  scope :scope_2 ->{ where(foo: "hello").reorder(bar: :asc) }
end

then

MyDoc.scope_1    #=> sorts by foo: 1, bar: 1;   I expected to have no sort

MyDoc.scope_2    #=> sorts by bar: 1 as expected

This is important in some cases when using indexes, sometimes a sort will cause MongoDB to skip using an index when using complex expressions.

johnnyshields avatar Sep 21 '14 20:09 johnnyshields

this might be a mongoid issue tho.. Not sure.

arthurnn avatar Sep 29 '14 15:09 arthurnn

The problem is scopes are criteria that gets merged with the existing criteria. In this case, the reorder by itself is ignored if there are no conditions. Something like .reorder(nil) to force it to clear the pre-existing order might be useful here.

johnnyshields avatar Sep 29 '14 21:09 johnnyshields