class Box
embeds_many :things
after_init :add_default_things
def add_default_things
self.things.build(title: "Socks", value: 2)
self.things.build(title: "Ring", value: 1)
end
end
class Thing
field :title
field :value, type: Integer
end
all boxes have got some default things: Socks and a Ring. Everybody can add this or another things into a box. So now I need to order all boxes by count of socks:
Box.order_by(:thing_with_title_socks.value.desc) # ???
I am not good at ruby so I am going to try to explain it in java terms. The problem is how you design your data. For example you have n Box classes, each having a list of items in it:
to sort all boxes in this classes for a specific item value you need to loop through all items in boxes which is not good at all. so I would change my code to do it more efficiently:
this way I would check if the item exists in box or not; access the items value with O(1) complexity, and I wouldn’t mistakenly put 2 different packets of socks in my box which would cause an error (which one would it sort for?).
your current data structure is like this :
but if you are going to do sorting / direct access (using in query) on “known” object (like ring or socks) then your data should look like:
if you have extra information attached to this items they can also look like :
this way you have direct access to the items in box.
hope this would help.
Edit : I thought it was obvious but just to make thing clear: you can’t efficiently query “listed” child data unless you know the exact position. (You can always use map/reduce though)