instance method
any?
Ruby on Rails 7.2.3
Since v4.0.13Signature
any?()
Returns true if the collection is not empty.
class Person < ActiveRecord::Base has_many :pets end person.pets.count # => 0 person.pets.any? # => false person.pets << Pet.new(name: 'Snoop') person.pets.count # => 1 person.pets.any? # => true
Calling it without a block when the collection is not yet loaded is equivalent to collection.exists?. If you’re going to load the collection anyway, it is better to call collection.load.any? to avoid an extra query.
You can also pass a block to define criteria. The behavior is the same, it returns true if the collection based on the criteria is not empty.
person.pets # => [#<Pet name: "Snoop", group: "dogs">] person.pets.any? do |pet| pet.group == 'cats' end # => false person.pets.any? do |pet| pet.group == 'dogs' end # => true
Source
# File activerecord/lib/active_record/associations/collection_proxy.rb, line 836
Defined in activerecord/lib/active_record/associations/collection_proxy.rb line 836
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::Associations::CollectionProxy