我有两个模型,它们之间有1到n的关系:
图书1 <-> n页
我确实想对所有的书(大约300,000本)做一份更新声明。图书模型有一个列interesting_pages_count,需要将所有有趣属性设置为true的页面进行汇总。
这在一份声明中是可能的吗?
谢谢你,马克勒斯
发布于 2012-01-07 17:42:24
至少在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;发布于 2012-01-07 16:01:50
你可以试试
Book.update_all({:field => value}, where_condition)
或者使用普通的SQL查询。
发布于 2012-01-07 16:02:10
好吧,只有一条语句是真正雄心勃勃的,但是如果您在您的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)}https://stackoverflow.com/questions/8770780
复制相似问题