Tuesday, 9 October 2012

Sort an array of objects by an attribute



Here is an example to sort an array of (the same kind of) objects by an attribute. Let's say you have an array of User objects that have the attributes 'name'
. First, find all
$ users. @users = User.find(:all)

Now, we have to sort this array by 'name'. Since we don't know if any user used capitals in his name or not, we use 'downcase' to sort without case sensitivity.

A small not. 'sort' returns a new array and leaves the original unchanged. You may want to just reorder the @users array, so use the 'sort!' method. The '!' indicates it's a destructive method. It will overwrite the current @users array with the new sorting. 

$ @users.sort! { |a,b| a.name.downcase <=> b.name.downcase }


Since strings are comparable, this will sort you user objects alphabetically by name.

That's all! :)

Tuesday, 2 October 2012

objects parent and child access

If we have an object profile.

$ x = Profile.all.first
 #<Profile _id: 506a8bc5a788000c6300002f, _type: nil>
to fetch the child details of the object we can have
$ x._children
[#<ProfileKidsType _id: 506a8bc5a788000c6300002e, _type: "ProfileKidsType", fname: "jyothi", lname: "k ", kids_id: "KL295170", nickname: "jyoths", gender: "Female", birthdate: 2012-10-02 00:00:00 UTC, food_allergies: "No", medical_issues: "No", special_needs: "No", other_concerns: "No", organization_memberships: nil>]
so we have the child details, this can have the parent details . so
$ y= x.kids_type
$ y._parent
#<Profile _id: 506a8bc5a788000c6300002f, _type: nil>

y._parent will be the parent details of the child object

here is an example: