2014-01-28 102 views
0

我可以從下面的代碼創建postgresql視圖嗎?是否有必要?因爲現在需要幾秒鐘才能加載,但將來我必須在其上添加日期範圍。如果是的話,有人可以幫我寫下它。Rails從活動記錄創建視圖

report = self.project_reports 
    results_total = report.where('value < ?', 50).group("key_id").select('key_id') 
    fifty = report.where('value BETWEEN ? AND ?', 41, 50).group("key_id").select('key_id') 
    forty = report.where('value BETWEEN ? AND ?', 31, 40).group("key_id").select('key_id') 
    thirty = report.where('value BETWEEN ? AND ?', 21, 30).group("key_id").select('key_id') 
    twenty = report.where('value BETWEEN ? AND ?', 11, 20).group("key_id").select('key_id') 
    ten = report.where('value BETWEEN ? AND ?', 4, 10).group("key_id").select('key_id') 
    three = report.where('value = ?', 3).group("key_id").select('key_id') 
    two = report.where('value = ?', 2).group("key_id").select('key_id') 
    one = report.where('value = ?', 1).group("key_id").select('key_id') 
    pos = {fif: fifty.count.size, four: forty.count.size, thir: thirty.count.size, twen: twenty.count.size, te: ten.count.size, thr: three.count.size, tw: two.count.size, on: one.count.size, result_t: total} 

回答

1

這會不會是在SQL意義上的真正的「視圖」(你只能創建通過DDL查詢),但你肯定可以建立一個ActiveRelation(這是你無論如何的意思大概是什麼)。請注意,您正在任意切換'數值'和'位置',這是故意的嗎?爲了一致起見,我在這裏使用「值」:

group_sql = <<-SQL 
    CASE WHEN value = 1 THEN 'one' 
     WHEN value = 2 THEN 'two' 
     WHEN value = 3 THEN 'three' 
     WHEN value <= 10 THEN 'ten' 
     WHEN value <= 20 THEN 'twenty' 
     WHEN value <= 30 THEN 'thirty' 
     WHEN value <= 40 THEN 'forty' 
     WHEN value <= 50 THEN 'fifty' 
SQL 
report = self.project_reports.where('value < 50').group(group_sql) 
positions = report.count 
positions['total'] = positions.values.sum 
+0

http://alexpotrykus.com/blog/2013/04/10/postgres-views-in-rails/這是不是視圖? – John

+0

如果你仔細閱讀那篇文章,你會發現實際的視圖直到以'create or replace view ...'開頭的遷移纔會出現。該聲明創建了一個視圖。運行任意查詢可以以與視圖類似的方式使用,但它會降低性能的靈活性。您通常不會開始使用視圖,除非您確定性能方面的好處證明了可維護性方面的困難。要麼是這樣,要麼就是如果你喜歡難以維護的代碼:)在這種情況下,我看不出有什麼理由讓你轉移到真實的視圖(物化或不)。 – PinnyM