Let's say I have some models: User
, Post
, and Vote
. A user has many posts and a post has many votes. Votes can be either an up vote or a down vote (stored as a boolean). What I am considering is the best way to do queries like these:
- All users, and the total number of up votes they've received.
- All users, and the post that has received the most up votes.
- All users, and the total number of votes (both up and down) they've received.
There are three ways I can think to do this, in increasing levels of efficiency:
Calculate vote counts in the controller using loops. This would potentially do a lot of extra queries and query data that I don't need, like each post and each vote record. For example (3rd query):
@users = User.all @vote_count = @users.posts.votes.count # retrieves every post and vote, which I don't need
Store the vote counts as fields in the User model and use callbacks to update those counts whenever a vote is made. This would make the query simpler, but I'd like to keep the models more loosely coupled and not have the user model's schema grow every time I need some sort of data on a related model.
Use some sort of query that will do these types of calculations via SQL and not look up more data than I need. This seems like the best choice, but I don't know how to approach it. Any suggestions/examples? Thanks!