我有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来做到这一点?
你说你的'product'模型有一个'purchase_count',但在你的查询中,你更新'purchases'表。 –
@ArunKumar对不起,固定那种类型 – Blankman