2016-08-22 87 views
0

我有2种型号:计算所有关联对象和更新计数

class Products < ActiveRecord::Base 
    has_many :purchases 

class Purchase < ActiveRecord::Base 
    belongs_to :Product 

产品型号有一栏purchase_count

我希望有一个非常快速有效的方式来更新这个计数器,基本上运行该SQL :

UPDATE products SET purchase_count = (SELECT COUNT(*) from purchases where active=1 and product_id = 123) where id = 123 

我可以用ActiveRecord来做到这一点吗?如果没有,我怎么能用raw sql来做到这一点?

+0

你说你的'product'模型有一个'purchase_count',但在你的查询中,你更新'purchases'表。 –

+0

@ArunKumar对不起,固定那种类型 – Blankman

回答

2

您应该使用counter_cache列以使其有效。 Rails允许您在belongs_to模型(purchase)中将counter_cache选项设置为true。但是您应该生成一个迁移以将表添加到products表中。

如需更多信息,寻找counter_cachehttp://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference

如果你只是不想指望所有相关的对象,而是需要传递的情况下,你需要一个定制counter cache。例如,看看http://douglasfshearer.com/2006/10/06/custom-counter-cache-with-conditions.html

+0

但我需要添加一个WHERE子句,它不仅仅是计算所有记录。此外,计数器缓存执行的查询是COUNT还是递增/递减? – Blankman

+0

@布兰克曼,啊,你需要一个'自定义计数器缓存'。见http://douglasfshearer.com/2006/10/06/custom-counter-cache-with-conditions.html –