I have a video_votes table with all the votes with a column called value set to 1 or -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
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:
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.