Rails - Delete all Records that Meet a Condition

后端 未结 4 618
刺人心
刺人心 2021-02-02 06:26

How do you write in the Rails way? I have a model - Managers. I want to delete all records from Managers that meet the condition that manager_level is 5.

Thank you.

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-02 06:49

    After Rails 5.1., We cannot pass conditions to delete_all/destroy_all method

    Manager.where(:manager_level => 5).delete_all
    

    This will run multiple queries to delete each record

    But in Rails 6, we can use delete_by to delete using condition,

    Manager.delete_by(manager_level: 5)
    

    This will run single delete query

    delete from managers where manager_level = 5

提交回复
热议问题