Skip to content

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#

#<<(element : T) : self#

Adds an element to the collection with dirty tracking.

View source

#[]=(index : Int, value : T) : T#

Sets the element at the given index with dirty tracking.

View source

#[]?(index : Int) : T | Nil#

Returns the element at the given index, or nil if out of bounds.

View source

#clear : Nil#

Removes all elements from the collection with dirty tracking.

View source

#delete(element : T) : T | Nil#

Removes an element from the collection with dirty tracking.

View source

#dirty? : Bool#

Returns true if the collection has been modified since its elements were last synchronized with the database.

View source

#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 --
View source

#includes?(element : T) : Bool#

Returns whether the collection contains the element.

View source

#initialize_collection : Nil#

Loads the collection's elements, unless they're already loaded.

View source

#inspect(io)#

View source

#remove_element(element : T) : Bool#

Removes an element and returns whether it was present.

View source

#size : Int32#

Returns the number of elements in this container.

View source

#to_a : Array(T)#

Returns a copy of the elements array.

View source

#unsafe_fetch(index) : T#

View source