Rails 7.0 adds functionality to Assert a Single Record

Rails 7.0 has introduced two methods sole and find_sole_by that are used to query the database for a unique record based on the provided constraints. This is very useful, especially when we want to fetch just a single row, or we want to assert that multiple records don’t exist based on the conditions that have been provided.

Before Rails 7.0

Suppose we want to find a product with said price price and it only has to be one:

1
2
3
4
5
6
7
8
9
product = Product.where(price: price).count

if product.count == 1
  puts product.first
elsif product.count == 0
  puts "No products found"
else
  puts "More than one product found"
end

The complexity with implementations such as above increases especially when we’ll need to query between multiple models to get our result.

After Rails 7.0

The find_sole_by method is similar in function to find_by, the only difference is that it asserts that the record being retrieved is the only one that exists. From the previous method, we can have a reduced form as below:

1
2
3
4
5
6
product = Product.find_sole_by(price: price)

# => ActiveRecord::RecordNotFound      (if no matching Product with the price provided)
# => #<Product ...>                    (if one Product with the price provided)
# => ActiveRecord::SoleRecordExceeded  (if more than one Product with the price provided)

For the method sole, its functionality is similar to first, however, it only extracts the results when it’s the only unique one matching the constraints provided.

1
2
3
4
5
6
product = Product.where(price: price).sole

# => ActiveRecord::RecordNotFound      (if no matching Product with the price provided)
# => #<Product ...>                    (if one Product with the price provided)
# => ActiveRecord::SoleRecordExceeded  (if more than one Product with the price provided)

More on this can be read here.