2010-12-15 51 views
14

假設我在我的Rails應用程序中有一個名爲'user_products'的表和一個名爲UserProduct的對應模型。我的桌子上也有一個名爲'is_temporary'的字段。現在假設我想運行這樣的查詢,但使用ActiveRecord的抽象層:使用一個查詢在Rails中與ActiveRecord同時更新多個記錄?

UPDATE user_products SET is_temporary = false WHERE user_id = 12345; 

有沒有一種方法,我可以做到這一點使用ActiveRecord?也許沿線的東西

UserProduct.find_by_user_id(12345).update_attributes(:is_temporary => false) 

我想只有一個查詢運行,爲此發生。

回答

16
UserProduct.update_all({:is_temporary => false}, {:user_id => 12345}) 
18
UserProduct.update_all({:is_temporary => false}, {:user_id => 12345}) 

雖然提防:此跳過所有驗證和回調,因爲沒有UserProduct的情況下都不會被實例化。

19

這是一箇舊帖子。我的情況下,更新了這個有人檢查它:)(軌道4)

DEPRECATION: Relation#update_all with conditions is deprecated. Please use Item.where(color: 'red').update_all(...) rather than Item.update_all(..., color: 'red'). 

所以查詢將

UserProduct.where(:user_id => 12345).update_all(:is_temporary => false) 

乾杯

+1

非常感謝,謝謝! – Sebastialonso 2014-05-12 06:14:39

+0

這似乎也適用於Rails 3 – lavaturtle 2015-07-22 18:57:48

相關問題