I have a controller method where I'm trying to pass a string with multiple order_by
arguments to return a sorted collection.
The order_by syntax works with one stringified argument, i.e.
order_param = "image_fize_size DESC"
query.order_by(order_param)
>> #<Mongoid::Criteria
selector: {...},
options: {:sort => {"image_file_size"=> -1}}
class: ...>
Due to mongoid transforming the string behind the scenes
Is there a certain syntax I can use to pass multiple arguments as one string to the order_by
method without any complex string manipulation required?
i.e.
order_param = "image_file_size DESC created_at DESC"
query.order_by(order_param)
# to hopefully yield a criteria that looks like:
>> #<Mongoid::Criteria
selector: {...},
options: {:sort => {"image_file_size"=> -1, "created_at" => -1 }}
class: ...>
CodePudding user response:
There are many ways to affect multiple sorts using order_by!
irb(main):001:0> query.order_by("image_file_size DESC, created_at DESC")
Some other ways:
irb(main):002:0> query.order_by(image_file_size: :desc, created_at: :desc)
irb(main):003:0> query.order_by(image_file_size: "desc", created_at: "desc")
irb(main):004:0> query.order_by(image_file_size: -1, created_at: -1)
irb(main):006:0> query.order_by([:image_file_size, -1], [:created_at, -1])
(This also accepts "desc", :desc)
irb(main):007:0> query.order_by(:image_file_size.desc, :created_at.desc)
=>
#<Mongoid::Criteria
selector: {}
options: {:sort=>{"image_file_size"=>-1, "created_at"=>-1}}
class: ...
embedded: ...>