Okay, lets say I got 2 different Models:
- Poll (has_many :votes)
- Vote (belongs_to :poll)
So, one poll can have many votes.
At the moment I’m displaying a list of all polls including its overall vote_count.
Everytime someone votes for a poll, I’m going to update the overall vote_count of the specific poll by using:
@poll = Poll.update(params[:poll_id], :vote_count => vote_count+1)
To retrieve the vote_count I use : @poll.vote_count which works fine.
Lets assume I got a huge amount of polls (in my db) and a lot of people would vote for the same poll at the same time.
Question :
Wouldn’t it be more efficient to remove the vote_count from the poll table and use: @vote_count = Poll.find(params[:poll_id]).votes.count
for retrieving the overall vote_count instead?
Which operation (update vs. count) would make more sense in this case?
(I’m using postgresql in production)
Thanks for the help!
Have you considered using a counter cache (see counter_cache option)? Rails has this built in functionality to handle all the possible updates to an association and how that would affect the counter.
It’s as simple as adding a 0 initialized integer column named
#{attribute.pluralize}_count(in your casevotes_count) on the table of one to many side of an association (in your case Poll).And then on the other side of the association add the
:counter_cache => trueargument to the belongs to statement.Now this doesn’t answer your question exactly, and the correct answer will depend on the shape of your data and the indexes you’ve configured. If you’re expecting your votes table to number in the millions spread out over thousands of polls, then go with the counter cache, otherwise just counting the associations should be fine.