tim*_*one 3 activerecord ruby-on-rails
有没有办法做到以下几点?:
>items=Item.where('location_id=?',8)
>items.count # 12; now delete all of them
>items.destroy
Run Code Online (Sandbox Code Playgroud)
我知道我可以这样做,Item.destroy_all('location_id=?',8)但我宁愿在进行破坏性操作之前进行计数以检查我的工作。
您可以通过ActiveRecord::Relation#destroy_all 方法来做到这一点:
items.destroy_all
Run Code Online (Sandbox Code Playgroud)
或者
Item.destroy_all(location_id: 8)
Run Code Online (Sandbox Code Playgroud)
每一条记录都会被一一销毁。如果您想快速删除它而不进行额外检查,请delete_all改用:
items.delete_all
# or
Item.delete_all(location_id: 8)
Run Code Online (Sandbox Code Playgroud)