Wednesday, February 15, 2012

Accessing a non model attribute through Rails Active Record Query Interface


Hi,

Imagine this is your scenario:-
You have a model called User. This users table in the back end has more

than 100 records.
I am trying to extract the TOP 30 records , grouping people by the total

number of residents in each area, ordering them in a descending manner. 

The sql query for the same is:- 


    select area, count(area) as total from users group by area order by

total desc limit 30; 


When doing this in Rails, the query looks something like this:- 


    User.select('area, count(area) as total').group('area').order('total

DESC').limit(30)
Rails Active Record Query Interface?
This gives me the areas in descending order, but it doesn't share the

count in terms of number of residents per area. Atleast not a direct outcome of the equivalent Rails command.
Now here come a few road blocks, something that I faced atleast..:)
1. How can we access the count attribute "total" through
2. How can we do 1. along with getting the TOP 30 records ?
3. How can we do 1., 2. and also get the records in the descending order ?
To get the count for each area the below query works, but it doesn't directly support our requirements as of 2 and/or 3.
User.select('area, count(location) as total').group('area').count
The reason behind this is,
a. Profile.select('location, count(location) as total').group('location').order('total DESC').count
b. Profile.select('location, count(location) as total').group('location').order('total DESC').limit(30).count
a. and b. throw errors via Rails console.
I got to know about use of "**to_sql**" from the [active record rails
casts][1] by Ryan Bates. 


  [1]:

http://railscasts.com/episodes/202-active-record-queries-in-rails-3 


When I used the to_sql command in my Rails query, I got:- 


    User.select('area, count(area) as total').group('area').order('total

DESC').limit(30).to_sql 


    SELECT  area, count(area) as total FROM `users` GROUP BY area ORDER

BY total DESC LIMIT 30 


I got the same sql query as above. But somehow since the **count(area)**

is not a direct attribute of the Users model, I was unable to print it

using the above Rails query. 


I'm able to get the count of residents belonging to each area using `User.select('area, count(area) as total').group('area').count`, 
but this is not giving me the areas in descending order. What it returns
is a hash having the area with the count of number of residents in it. I couldn'tfind much from the Rails Guides on this .

Now what worked for me like a charm thanks to inputs from Frederick Cheung(via the following thread - http://www.ruby-forum.com/topic/3073356) was:-

users = User.select('area, count(area) as total').group('area').order('total DESC').limit(30)

users[0].total

This is how through a loop we can access the total number of folks residing in other areas as well.

Hope this helps.

Thanks..:)

Saturday, February 11, 2012

The Drawing Competition at Anatha Shishu Sevashrama - Cognizant CSR



In life, one is not always blessed with opportunities where each one can show case their talent. Such opportunities come, not often. These come by even more scarcely for the less fortunate. The Drawing competition at Anatha Shishu Sevashrama, a home for around 65 orphans, was such an initiative where these children could bring out their hidden talent.



The entire event was something that started as a thought in the mind of Kalyani Sekhar, Sr Director - DAG. At first, it was an event that Kalyani wanted to hold for these children during Children's day, around November last year. Due to some unforseen reasons the event got postponed and was finally held on January 7th, 2012.  Kalyani, was very actively involved in entire planning and execution of this event from the very beginning. Being a POC at this ashram, it was a wonderful opportunity for me also to be involved alongside.


Conducting this event for around 65 children, surely had its bit of planning involved, to make sure everything went well. Children in the ashram were of different age groups from LKG upto 11th std. To start with, we had to figure out how it should be conducted for 60+ children simultaneously. Once the list of the children belonging to different classes was obtained from the ashram, we divided them into junior, middle and senior age groups for the competition. Topics had to be finalized on which these children could draw. It was decided that the senior age group children would draw and paint, whereas the junior and the middle age group children would mainly use pencil colors and crayons for the competition. 

When it came to choosing stationery for the competition and prizes for the children, Kalyani wanted to give them the best they could make use of. My father, was mainly into stationery business, so I suggested we could do well with having him as a vendor to procure the necessary items for this competition. Through this, selection of good quality items was made easier with the vast experience my father in the stationery business. It was also a unique opportunity for me to do a bit of management, execution :), something different from the normal role that I have at office..:).  We brainstormed from the word go, upon the variety of items, quantity and suitable sizes of items to meet requirements of various age groups before placing a final order, this way making sure that nothing is missed out on the day of the competition. Items used for the competiton included drawing sheets, boxes of pencils, sufficient quantities of erasers, sharpeners, color pencils, crayons especially for the use of little ones :), paint colors, palettes, plastic cups used for containing water required while painting, etc.


When it came to choosing prizes, as a token of appreciation of one's exceptional effort, it was decided that these children get rewared with something they could really make good use of. It was agreed upon to give away 3 prizes for each of the 3 age groups of children i.e. junior, middle and senior groups. Upon consulting Saraswathy aunty(the General Secretary and the care taker of the ashram, a lady who has lost her sight of vision) for the same, it was decided to give a variety of stationery items, each forming a set, as a prize to each winner. This could be put to good use in their daily schooling. For the lower age groups especially, Kalyani suggested we could give them drawing and coloring books with lesser number of stationery items as they wouldn't really require too much stationery for their age. Most of the children in the ashram, are currently going to Kannada medium schools and are more fluent in the local language of the city. Probably, keeping this in mind Kalyani also suggested that the lower age groups can be gifted moral story books written in Kannada as part of their prizes. We, somehow managed to get the Kannada books of famous personalities like Mother Teresa, Bhagat Singh etc. to be a part of the prizes for the junior category of students. On a general note, a prize set included note books of various sizes, gel and ball pens, refills, box of color pencils, crayons, stick files (to keep important certificates), highlighter pens etc. The number and the variety of these items was accordingly moderated based on I, II and III prize categories. Based on her experience, Saraswathy aunty also suggested it would be good if consolation prizes could be given away to all the participants. A small notebook, a box of pencils and a ball pen, together gift wrapped as a set was
given to each participant of the competition towards the end.


      Saraswathy Aunty

I still can recall the mailer for this event was sent on Jan 5th, 2012 to Cognizant All BLR DL, and from then on, till 6th Jan EOD there were many volunteers who signed up for this event. Being a POC for this event, I started receiving queries wrt the event from Jan 5th itself..:). Associates wanted to know more details about this event, location specific queries and they also wanted us to confirm their participation . It was a little difficult for me to juggle between work and also answering the queries through IM, mails, vnet calls of the interested participants of this event but some how all went really well..:). It was also fun and exciting to see their enthusiasm to be a part of this altogether.. I am thankful to my team for believing in me that I could balance both work as well as this.

Going by the number of registered volunteers, I was pretty sure that there would be around 15 - 20 volunteers who would have registered for this event. Honestly, I was not sure at that point of time how we could really make best use of these many volunteers at the event, in a way they such that they also feel content with what they can contribute to a noble cause. Although, initially we had in the mailer mentioned we would need around 10 volunteers for this event, Rajesh the POC of Outreach Bangalore suggested that let the volunteers register for this event, even if it exceeds the required number. I just realized at that point, their physical presence in itself at the event has its own value, thereby they can witness the live event and do their bit of participation. Also they say right.., don't worry, things by itself will fall in place.. You just need to have faith.. this is just what happened..:) do read on..:)..

On the day of the event, it was really fulfilling to see a total of 26 volunteers! , who actually made it. It was truly amazing and mind boggling..!:).  We had associates from MBP,GVC,BTP and even a member from the newly acquired CoreLogic Team. One of the associates had also come with his family( his little one, wife and mother in law) for this event. Deepak Prabhu Matti, a member of the Bangalore Outreach Council Board, who has been actively involved with Cognizant Outreach Bangalore initiatives in many ways,  suggested that we could have each volunteer mentor a group of children during the competition. This way all volunteers were actively involved in the entire event.




Some volunteers were enjoying themselves with the little ones who as their age suggests, would generally be upto some or the other mischief..:), drawing and scribbling their way through the competition..:), other volunteers were helping by transferring childrens thoughts on what they had in mind to draw to the actual drawing paper... A truly wonderful bonding seemed to build between these children and the volunteers at that time..:).. Joy was all over at the ashram..:)



After the competition the and just before the prize distribution, Deepak Prabhu Matti, Rajesh had addressed all the volunteers gathered together briefing them about Outreach, Cognizant Foundation(CF) and current Outreach initiatives in Bangalore. This was never planned, it just happened I guess seeing the huge response we had for this event. I also got a chance to speak to the volunteers and share what activities have been previously conducted at this ashram as part of Cognizant Outreach initiatives and show them around the library and the dispensary constructed at the ashram that was donated by CF with Deepak Prabhu Matti being the lead volunteer behind this entire project initiative.




All in all it has truly being an enriching experience for me..:) . It is more fullfilling whenever I get to recall the series of events that lead to this event as a whole through this blog. It was a pleasure to work alongside a richly experienced, highly knowledgable person like Kalyani for this event. I still remember Kalyani's words as the event was drawing its end on that day, "it is really heartening to see these many volunteers". A major highlight of this entire event was, to see these many volunteers at the event, 26 Cognizant volunteers!.


It truly has been a wonderful beginning to 2012..:), sharing our joy with these children and many more in the days to come with support from volunteers, guidance from seniors and also with support from our company Cognizant, in initiatives like these. I humbly take this opportunity to thank each and every one who made this event successful..:)