2012-01-07 74 views
0

我有兩個型號,一個1到n關係模型之間:的ActiveRecord如何更新的相關1計數到n模型

書1 < - > N尋呼

我想在所有圖書上做一個更新聲明(約300'000)。 Book模型有一列interesting_pages_count,需要從所有頁面中摘出哪些有趣的屬性設置爲true。

這是可能的一個聲明?

感謝, Makrus

回答

0

你可以嘗試用

Book.update_all({:field => value}, where_condition)

或普通的SQL查詢。

0

嘛,只有一個語句實在是雄心勃勃的,但如果你對你的Book模型定義了這個方法:

def count_interesting_pages 
    self.pages.inject(0) { |result, page| result += 1 if page.interesting?} 
end 

然後,你可以這樣做:

Book.all.each {|b| b.update_attribute(:interesting_pages, count_interesting_pages)} 
1

這是可能的,至少在PostgreSQL中:

UPDATE books SET interesting_pages_count = (
    SELECT count(*) FROM pages WHERE pages.book_id = books.id AND interesting = true 
) FROM pages WHERE books.id = pages.book_id;