2011-09-03 17 views
1

在我的模型中,我經常擁有has_many關聯。我還經常需要顯示有多少(即assoc.count)。這會強制執行另一個查詢,如下所示:如何在ActiveRecord查詢中包含association.count以便它不執行第二個查詢?

ruby-1.8.7-p334 :020 > Instructor.first.instructors_lessons.count 
    Instructor Load (0.5ms) SELECT `users`.* FROM `users` INNER JOIN `instructor_profiles` ON `instructor_profiles`.`instructor_id` = `users`.`id` LIMIT 1 
    SQL (1.2ms) SELECT COUNT(*) FROM `instructors_lessons` WHERE (`instructors_lessons`.instructor_id = 2817) 

這是罰款時,有一個或兩個,但是當有100+,這個過程中得到明顯緩慢。 請看這個過程非常緩慢(http://pastebin.com/p4Sj7q7s)。我一直在用緩存解決一個非常緩慢的頁面。

,我可以把這個像這樣的查詢:但這是乏味和親切的失敗,我覺得ActiveRecord關聯的目的:

select("instructors.*, count('instructors_lessons.instructor_id') as num_lessons"). 

但我不能簡單地說instructor.lessons.count ...

有沒有辦法使用joins()或includes()以便這個額外的COUNT()查詢不需要執行?

回答

7

聽起來像你正在尋找counter cache

您只需使用_count創建一列,然後在您所屬的關聯中指定counter_cache。

在你的情況下,你會添加一個名爲「lessons_count」到你的教練專欄。然後執行以下操作:

belongs_to :instructor, :counter_cache => true 

當總關聯記錄更改時,此值將自動更新總數。

相關問題