Jus*_*zer 2 ruby database ruby-on-rails ruby-on-rails-3
我有一个video_votes表,其中所有的投票都有一个名为value的列设置为1或-1.我想总结视频投票的所有价值并显示净投票数.首先,我应该如何总结,其次,我应该将这个值存储在我的视频表中吗?如果是这样,怎么样?
我会从这开始,直到性能成为一个问题:
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
Run Code Online (Sandbox Code Playgroud)
一旦性能成为一个问题,我想缓存总和值,我可能会做这样的事情:
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
Run Code Online (Sandbox Code Playgroud)
查看关于"覆盖默认访问者"的AR文档(向下滚动一下) http://ar.rubyonrails.org/classes/ActiveRecord/Base.html