class Athena::ORM::PersistentCollection(T)
inherits Athena::ORM::AbstractLazyCollection
#
ORM-aware collection with dirty tracking and lazy loading support. Tracks changes since the last snapshot for computing insert/delete diffs.
The ORM puts one in every AORM::Collection field it manages, see AORM::Collection for how that happens.
The ORM creates it; application code doesn't construct one.
Lazy loading#
A collection on an entity loaded from the database doesn't load its elements until it's first read.
Reading it in any way, such as #size, #each, #[]?, #includes?, #to_a, #delete, #clear or #remove_element, loads every element with a single query.
Adding elements with #<< doesn't load it; elements added before it's loaded are kept alongside the loaded ones.
user = em.find! User, 1 # Doesn't query the user's groups
groups = user.groups.as AORM::PersistentCollection(Group)
groups.loaded? # => false
user.groups.size # Loads the groups
groups.loaded? # => true
Warning
Loading the collections of many entities one at a time issues one query per collection.
Change tracking#
Modifying the collection marks it #dirty?.
On the next flush, the elements added and removed since it was loaded, or last flushed, are written to the join table of an owning-side AORMA::ManyToMany association.
Methods#
#[]=(index : Int, value : T) : T#
Sets the element at the given index with dirty tracking.
#[]?(index : Int) : T | Nil#
Returns the element at the given index, or nil if out of bounds.
#delete(element : T) : T | Nil#
Removes an element from the collection with dirty tracking.
#dirty? : Bool#
Returns true if the collection has been modified since its elements were last synchronized with the database.
#each : Nil#
Calls the given block once for each element in self, passing that
element as a parameter.
a = ["a", "b", "c"]
a.each { |x| print x, " -- " }
produces:
a -- b -- c --
#initialize_collection : Nil#
Loads the collection's elements, unless they're already loaded.
#remove_element(element : T) : Bool#
Removes an element and returns whether it was present.