有沒有辦法做到以下幾點?:如何摧毀在Rails的一個ActiveRecord關係4.2
>items=Item.where('location_id=?',8)
>items.count # 12; now delete all of them
>items.destroy
我知道我能做到Item.destroy_all('location_id=?',8)
但我寧願做一個計數之前破壞性檢查我的工作操作。
THX
有沒有辦法做到以下幾點?:如何摧毀在Rails的一個ActiveRecord關係4.2
>items=Item.where('location_id=?',8)
>items.count # 12; now delete all of them
>items.destroy
我知道我能做到Item.destroy_all('location_id=?',8)
但我寧願做一個計數之前破壞性檢查我的工作操作。
THX
您可以通過ActiveRecord::Relation#destroy_all
method做到這一點:
items.destroy_all
或
Item.destroy_all(location_id: 8)
每個記錄將被擊破。如果你想快速刪除它,而無需額外的檢查,使用delete_all
代替:
items.delete_all
# or
Item.delete_all(location_id: 8)
的
的方法被稱爲#destroy_all
。
items.destroy_all
所以我想先做一個查找,通過計數驗證,然後銷燬所有這些; destroy_all需要一個條件,然後銷燬它們 – timpone
@timpone這將按要求工作......您不需要實例方法的條件。你甚至嘗試過嗎? –
可能重複[你如何在活動記錄中刪除?](http://stackoverflow.com/questions/4177686/how- do-you-delete-in-active-record) –
@BradWerth不是笨蛋 – timpone
是的。看問題中的第3點。這正是你想要做的。請注意,該問題的答案與此答案完全相同。在千萬個問題中,你真的認爲你是第一個問如何在rails中刪除某些東西的人嗎?這只是50個可能的候選人中最明顯的...... –