2012-10-27 62 views
3

我想基於poll_records表更新users表中的number_of_votes。在軌道上,它看起來像基於計數的更新

User.all.each do |user| 
    user.number_of_votes = user.poll_records.where("poll_record_type = 3").size 
    user.save 
end 

我是PostgreSQL的新手。我如何以這種方式更新用戶?

回答

4

可能是這樣的:

UPDATE users u 
SET number_of_votes = p.ct 
FROM (
    SELECT users_id, count(*) AS ct 
    FROM poll_records 
    WHERE poll_record_type = 3 
    GROUP BY users_id 
    ) p 
WHERE u.users_id = p.users_id 
AND  u.number_of_votes IS DISTINCT FROM p.ct; -- to avoid empty updates 

我不會用(保留字)或混合大小寫標識符作爲表名。它強制雙引號。

+0

Psst:在AND之前加'where 1 = 1'。 – wildplasser

+0

@wildplasser:修正了WHERE子句,thanx。 –