delete_by destroy_by rails 6
By Abhishek Kanojia on February 2, 2020
Rails 6 adds delete_by & destroy_by
Rails 6 provide with some extra stuffs added to it lately which simplifies the daily tasks. In this post we will be discussing two methods delete_by and destroy_by provided in Rails 6.
delete_by
delete_by provides an easier way to delete the Active Record instance by condition provided as an argument to delete_by method. Here is how it works:
# Previously
Person.where(name: 'John Doe').delete_all
# Now
Person.delete_by(name: 'John Doe')
destroy_by
Similarly, destroy_by uses destroy_all in place of delete_all for its operation. Usage:
# Previously
Person.where(name: 'John Doe').destroy_all
# Now
Persion.destroy_by(name: 'John Doe')
Few Things worth noting about both of the methods:
delete_by
- Internally uses delete_all
to perform the operation.
destroy_by
- Internally uses destroy_all
to perform the operation.
See Pull Request for more info.