Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-3758

"no implicit conversion of String into Integer" when ordering by embedded value

    • Type: Icon: Task Task
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 5.1.0
    • Affects Version/s: None
    • Component/s: None

      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?

            Assignee:
            emily.stolfo Emily Stolfo
            Reporter:
            KHMtravel KHMtravel [X]
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: