I was trying to order by the first value of an embedded array:
options [ { bookings => [ { price => 5 , ...}, { price => 6 , ...} ], name => "blah" }, { bookings => [ { price => 1 , ...}, { price => 2 , ...} ] name => "blahblah" } ]
My query that should returnthe option with the name "blahblah" as first option:
> options.order_by("bookings.0.price ASC").to_a
gave this error:
> TypeError: no implicit conversion of String into Integer
from /home/marc/.rvm/gems/ruby-2.1.2/gems/mongoid-4.0.0/lib/mongoid/extensions/hash.rb:104:in `[]'
I looked into it and changed the nested-method to:
def __nested__(string) keys = string.split(".") value = self keys.each do |key| # if value is Array -> convert to Integer if value.kind_of?(Array) #key is Integer nested = value[key.to_i] else #key is String nested = value[key] end value = nested end value end
This works for me.
I checks wether value is an array and converts the key to an integer.
Does this change have any unwanted consequences?