How to get the resultant array from a Mongoid::Criteria without an "each" block
Asked Answered
M

3

28

Our application uses ajax very heavily and as a result of this we have statements like var items = #{@items.to_json} in all our views. Now @items is being set in the controller as @items=Item.all. The problem is that @items is a Mongoid::Criteria and it doesn't have a .to_json method. So, it's throwing up an error while rendering the view. Is there an easy way to convert this criteria object into an array without using code like @items.collect {|i| i}

Matrices answered 21/12, 2010 at 11:26 Comment(0)
S
60

Use the #entries method in criteria to do request:

@items = Item.all.entries
Syllabus answered 21/12, 2010 at 13:12 Comment(1)
Hello shingara, can that work in opposite way? I mean convert array to Mongoid::Criteria.Lachlan
P
3

Actually, the solution I'm applying is to transform in an Array, so I can still use the power of criteria and then get the results. After you transform to array, you can transform in json

@items.to_a #give you the records

@items.to_a.to_json # give you the final json

Plutocrat answered 21/12, 2010 at 22:35 Comment(0)
G
1

FWIW, at least since Mongoid 4.0, there's the as_json instance method:

Person.where(:title => "Sir").as_json

Reference: http://rdoc.info/github/mongoid/mongoid/Mongoid/Criteria#as_json-instance_method

Gelasius answered 2/7, 2014 at 19:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.