Let’s say I have a rails app with 3 tables, one for questions, one for options (possible answers to this question), and one for votes.
Currently, when requesting the statistics on a given question, I have to make a SQL query for each option which will look in the “votes” table (around 1.5 million entries) and count the number of times this option has been selected. It’s slow and takes 4/5 seconds.
I was thinking of adding a column directly in the question table which would store the statistics and update them each time someone makes a vote. Is that good practice ? Because it seems redundant to the information that is already in the votes table, only it would be faster to load.
Or maybe I should create another table which would save these statistics for each question ?
Thanks for your advice !
Rails offers a feature called
counter_cachewhich will serve your purposeAdd the counter_cache option to votes model
and the following migration
This should increment the
votes_countfield in questions table for every new record in votes tableFor more info: RailsCast