jeudi 12 mars 2015

How to annotate a query with column from a relation?


Vote count:

0




Say I have two models, Owner and Dog. Dogs belong to Owners and Owners have many Dogs.


Can I query for Owners and annotate them with most_food_needed_for_pet, which is the food_needed column of the Dog with the max lifespan? I know I can accomplish this with multiple queries but I this should be possible with only one query using Arel.


My initial attempt was


Owner. joins(:dogs). select(Dog.arel_table[:food_needed].as('most_food_needed_for_pet')). select(Dog.arel_table[:lifespan].maximum). group('dogs.owner_id')


But that incorrectly annotates each owner with the max lifespan, and the food_needed of the first Dog in the database instead of the longest living Dog.



asked 1 min ago

troq

582






How to annotate a query with column from a relation?

Aucun commentaire:

Enregistrer un commentaire