Rails,数据结构和性能 [英] Rails, data structure and performance
问题描述
假设我有一个包含3个表格的rails应用程序,一个用于问题,一个用于选项(可能的答案为这个问题),一个用于投票。
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.
,当请求关于给定问题的统计信息时,我必须对每个选项进行SQL查询,查找投票表(大约150万个条目)并计算该选项的选择次数。它很慢,需要4/5秒。
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提供了 counter_cache
这将满足您的目的
Rails offers a feature called counter_cache
which will serve your purpose
向投票模式添加counter_cache选项
Add the counter_cache option to votes model
class Vote < AR::Base
belongs_to :question, :counter_cache => true
end
和以下迁移
add_column :questions, :votes_count, :integer, :default => 0
这会增加 votes_count
投票表中每个新记录的问题表
This should increment the votes_count
field in questions table for every new record in votes table
有关详情: RailsCast
这篇关于Rails,数据结构和性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!