delete_by destroy_by rails 6


Rails 6 Tutorials - SapidLabs

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.

Recommended Posts

Default Enum in Rails 6
Rails 6 provides a way to define default enum value. Let’s see how it works...
Ruby 2.7 adds Enumerable#tally
After introducing the Enumerable#tally method in Ruby 2.7-preview updates. #tally as the name suggests gives...
How to rename column name in Rails
Rails rename_column Rails provides a simple method rename_column which can be used in a migration....