Ruby on Rails/ActiveRecord/Aggregations

Active Record implements aggregation through a macro-like class method called composed_of for representing attributes as value objects. It expresses relationships like "Account [is] composed of Money [among other things]" or "Person [is] composed of [an] address". Each call to the macro adds a description of how the value objects are created from the attributes of the entity object (when the entity is initialized either as a new object or from finding an existing object) and how it can be turned back into attributes (when the entity is saved to the database).

Now it’s possible to access attributes from the database through the value objects instead. If you choose to name the composition the same as the attributes name, it will be the only way to access that attribute. That’s the case with our balance attribute. You interact with the value objects just like you would any other attribute, though:

Value objects are immutable and interchangeable objects that represent a given value such as a Money object representing $5. Two Money objects both representing $5 should be equal (through methods such as == and <=> from Comparable if ranking makes sense). This is unlike entity objects where equality is determined by identity. An entity class such as Customer can easily have two different objects that both have an address on Hyancintvej. Entity identity is determined by object or relational unique identifiers (such as primary keys). Normal ActiveRecord::Base classes are entity objects.

It’s also important to treat the value objects as immutable. Don‘t allow the Money object to have its amount changed after creation. Create a new money object with the new value instead. This is exemplified by the Money#exchanged_to method that returns a new value object instead of changing its own values. Active Record won’t persist value objects that have been changed through other means than the writer method.

The immutable requirement is enforced by Active Record by freezing any object assigned as a value object. Attempting to change it afterwards will result in a TypeError.