此:
Org.update_counters org.id, :users_count => org.users.length
基本上做到這一點:
update orgs
set users_count = coalesce(users_count, 0) + #{org.users.length}
where id = #{org.id}
展開了一步:
update orgs
set users_count = coalesce(users_count, 0)
+ (select count(*) from org_users where org_id = #{org.id})
where id = #{org.id}
現在你已經包裹在一個Org.find(:all).each
所以我們只需要迭代推入SQL和處理#{org.id}
:
update orgs o
set users_count = coalesce(users_count, 0)
+ (select count(*) from org_users ou where ou.org_id = o.id)
如果你真的要設置的users_count
值,而不是增量他們:
update orgs o
set users_count = (select count(*) from org_users ou where ou.org_id = o.id)