這裏是我是如何做到這一點。 在Rails 3和4中,我爲ActiveRecord :: Relation編寫了一個初始化程序。
首先,在Rails 3中:
class ActiveRecord::Relation
HUGE_COUNT = 20000
def count(column_name = nil, options = {})
exact, has_conditions = false, false
h = (column_name.class == Hash ? column_name : options)
exact = h[:exact]
has_conditions = h[:conditions]
has_distinct = (column_name.class == String) && (column_name =~ /\bdistinct\b/i)
h = h.except(:exact) # Remove it because super won't understand it
column_name.class == Hash ? column_name = h : options = h
if exact || has_conditions || has_distinct
super
else
est = estimated_count
est > HUGE_COUNT ? est : super
end
end
def estimated_count
node = connection.execute("EXPLAIN #{self.to_sql}").first
match = node['QUERY PLAN'].match(/rows=\d+\b/)
match ? match[0].split('=').last.to_i : 0
end
末
軌道4,5是除了一樣:
def estimated_count
node = {}
connection.unprepared_statement do
node = connection.execute("EXPLAIN #{self.to_sql}").first
end
match = node['QUERY PLAN'].match(/rows=\d+\b/)
match ? match[0].split('=').last.to_i : 0
end
因爲到目前爲止,我發現,這是HUGE_COUNT低一般非常精確到1%或2%以內。這對我的需要很好,但顯然這是相當危險的......
我不相信鐵軌這樣做(並且不能關閉選項) – OneChillDude