[英]Ruby on Rails: How do I sum up these elements in my database?
I have a video_votes table with all the votes with a column called value set to 1 or -1. 我有一个video_votes表,其中所有的投票都有一个名为value的列设置为1或-1。 I want to sum up all the values of the video's votes and display that net vote count.
我想总结视频投票的所有价值并显示净投票数。 First, how should I sum this up, and second, should I store this value in my video table?
首先,我应该如何总结,其次,我应该将这个值存储在我的视频表中吗? If so, how?
如果是这样,怎么样?
I would start with this until performance became an issue: 我会从这开始,直到性能成为一个问题:
class Video < AR::Base
has_many :video_votes
def vote_sum
video_votes.sum(:value)
end
end
class VideoVote < AR::Base
belongs_to :video
validates_inclusion_of :value, :in => [-1,1]
end
Once performance became an issue and I wanted to cache the summed value I might do something like this: 一旦性能成为一个问题,我想缓存总和值,我可能会做这样的事情:
class Video < AR::Base
has_many :video_votes
# Override vote_sum attribute to get the db count if not stored in the db yet.
# The alternative is that you could remove this method and have the field
# populated by a migration.
def vote_sum
read_attribute(:vote_sum) || video_votes.sum(:value)
end
end
class VideoVote < AR::Base
belongs_to :video
validates_inclusion_of :value, :in => [-1,1]
after_create :update_video_vote_sum
private
def update_video_vote_sum
video.update_attributes(:vote_sum => video.vote_sum + value)
end
end
Check out the AR documentation on "Overwriting default accessors" (scroll down a bit) http://ar.rubyonrails.org/classes/ActiveRecord/Base.html 查看关于“覆盖默认访问者”的AR文档(向下滚动一下) http://ar.rubyonrails.org/classes/ActiveRecord/Base.html
In your Video model: 在您的视频模型中:
def total_votes
self.votes.sum(:value)
end
So an example might be: 所以一个例子可能是:
@video.total_votes
I'm to sum 2 fields on the level a model: 我要在一个模型的级别上总结2个字段:
def update_sum_times
update_attribute(:sum_of_fields, calc_two_dates)
end
def calc_two_dates
date_one + date_two
end
Use ActiveRecord's sum
method. 使用ActiveRecord的
sum
方法。
VideoVote.sum('value')
You shouldn't store it in the same table. 您不应将其存储在同一个表中。 If you have other fields you want to summarize then create a "summary" table and periodically summarize the fields and store the values there.
如果您要汇总其他字段,请创建“汇总”表并定期汇总字段并将值存储在那里。 ActiveRecord's other calculation methods might be of interest in that case.
在这种情况下,ActiveRecord的其他计算方法可能会引起关注。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.