Jul 02, 2022 | Ruby
ActiveRecord is beautiful and powerful. Here is how .many? and .any? methods work.
Instead of doing something like collection.size > 1, you can do it with collection.many? like this:
garage.vehicles.count # => 2
garage.vehicles.many? # => true
You can even pass a block to define a criteria like this:
garage.vehicles.many? do |vehicle|
vehicle.brand == "BMW"
end
This method checks if a collection has at least one record, and if it does it returns true:
garage.vehicles.count # => 0
garage.vehicles << Vehicle.new(brand: "BMW")
garage.vehicles.count # => 1
garage.vehicles.any? # => true
This method, same as .many? can also take a block to define a criteria:
garage.vehicles.any? do |vehicle|
vehicle.brand == "BMW"
end
The important thing to know here is that, when the collection is not yet loaded (you didn't call garage.vehicles yet), when you call a .any? method it behaves the same as if you would call .exists? method.
If you are planning to load the collection anyways, it's better to call garages.vehicles.load.any? to avoid an extra query.