Queries for rails4

cherry-pick a few commits from #766 , which are compatible with rails 3.2 , so we can merge right now at master, and slowly push towards rails 4.x 

review @dwradcliffe 
cc @georgedrummond