Define model associations with references and collections
masterOhm uses references and collections to represent relationships between models.
References
reference :field, :Model is a shortcut that:
- Adds an attribute for the foreign key (e.g.,
post_id). - Creates an
indexon that foreign key. - Defines a setter
field=(model)that sets the ID. - Defines a getter
fieldthat returns the associated model instance (memoized).
Collections
A collection is a macro that defines a finder method. It assumes an index exists on the foreign key in the target model. You can declare it explicitly or use inference.
Example Implementation
class Post < Ohm::Model
attribute :title
attribute :body
collection :comments, :Comment
end
class Comment < Ohm::Model
attribute :body
reference :post, :Post
endIn this setup, post.comments returns a collection of Comment instances, and comment.post returns the associated Post object.