Rails 7 adds ActiveRecord::FinderMethods#sole


default-enum-in-rails

Rails 7 adds method sole and find_sole_by in ActiveRecord::FinderMethods, which enables you to get sole or single record by the attributes defined, and also asserts that there aren’t multiple rows matching the condition.

Example usage of sole

Product.where(name: 'Test').sole
# => ActiveRecord::RecordNotFound ( If no record is found )

# => #<Product ..> ( If single record is found )

# => ActiveRecord::SoleRecordExceeded ( If more records are found with given name )

Example usage of find_sole_by

Product.find_sole_by(name: 'Test')
# => ActiveRecord::RecordNotFound ( If no record is found )

# => #<Product ..> ( If single record is found )

# => ActiveRecord::SoleRecordExceeded ( If more records are found with given name )


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...