Thursday, May 5, 2011

Code Sample: my first complex Active Record Query

I experienced something the other day in Active Record. My seasoned pairing partner and I used it to do a SQL query to Active Record to pull one chunk of data that matched several criteria out of a database of many users, in many communities, that had many modes of transportation, that had all traveled different numbers of miles using those different modes of transportation. We needed the one user who had traveled the most number of miles by bicycle.

 biker_miles = User.joins(:trips => :mode).where(:modes => {:name => 'Bike'}).sum(:distance, :group => :user_id) biker_miles.max { |a,b| a[1].to_i <=> b[1].to_i }                                                                      

I need to pick this apart to really understand what it does, but I know it pulled the data we needed. It seems like this is just the magic that makes RoR so spectacular. It's like the salt on my popcorn...the cream in my coffee. More on this later.

No comments:

Post a Comment