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 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')


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

Rails 5 adds OR Activerecord method
This or method was introduced in Rails 5, It returns a new ActiveRecord::Relation which is...
Descendants vs Subclasses in Ruby
Descendants has been a part of Rails ActiveSupport::DescendantsTracker for quite a while. However, Class#subsclasses is...
Ruby 3.1 adds subclasses method
Ruby 3.1 adds Class#subclasses method, which returns an array of subclasses directly inheriting from the...