或者,您可以完全避開Vote
表並保留一個外部帳簿。
每次投票時,都會調用一個單獨的理貨類,以保持投票的投票數。每天會有一個理貨記錄。統計記錄將有一個整數,表示當天投票的數量。
對Tally類的每個增量調用將查找當前日期(今天)的計數記錄,增加投票計數並保存記錄。如果沒有記錄存在,則會創建一個並相應地增加。
例如,讓我們有一個名爲VoteTally
的類,它具有兩個屬性:日期(日期)和投票計數(整數),沒有時間戳,沒有關聯。這裏的模式將是什麼樣子:
class VoteTally < ActiveRecord::Base
def self.tally_up!
find_or_create_by_date(Date.today).increment!(:votes)
end
def self.tally_down!
find_or_create_by_date(Date.today).decrement!(:votes)
end
def self.votes_on(date)
find_by_date(date).votes
end
end
然後,在Vote
模式:
class Vote < ActiveRecord::Base
after_create :tally_up
after_destroy :tally_down
# ...
private
def tally_up ; VoteTally.tally_up! ; end
def tally_down ; VoteTally.tally_down! ; end
end
這些方法將獲得投票數:
VoteTally.votes_on Date.today
VoteTally.votes_on Date.yesterday
VoteTally.votes_on 3.days.ago
VoteTally.votes_on Date.parse("5/28/13")
當然,這是一個簡單的例如,你將不得不適應它來適應。這將在投票時導致額外的查詢,但它比沒有索引的100M記錄上的where
子句要快得多。這個解決方案可能有些微不準確,但我認爲這是可以接受的,因爲每日投票計數的軼事性質。
這裏有什麼問題? – Substantial
@gg_s查詢在這張桌子上執行「計數」並帶有日期條件永久或不工作 – Emmanuel