Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like “Project has one Project Manager” or “Project belongs to a Portfolio”. Each macro adds a number of methods to the class which are specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby’s own attr*
methods.
class Project < ActiveEntity::Base
belongs_to :portfolio
has_one :project_manager
has_many :milestones
has_and_belongs_to_many :categories
end
The project class now has the following methods (and more) to ease the traversal and manipulation of its relationships:
-
Project#portfolio
, Project#portfolio=(portfolio)
, Project#reload_portfolio
-
Project#project_manager
, Project#project_manager=(project_manager)
, Project#reload_project_manager
-
Project#milestones.empty?
, Project#milestones.size
, Project#milestones
, Project#milestones<<(milestone)
, Project#milestones.delete(milestone)
, Project#milestones.destroy(milestone)
, Project#milestones.find(milestone_id)
, Project#milestones.build
, Project#milestones.create
-
Project#categories.empty?
, Project#categories.size
, Project#categories
, Project#categories<<(category1)
, Project#categories.delete(category1)
, Project#categories.destroy(category1)
A word of warning
Don’t create associations that have the same name as instance methods of ActiveEntity::Base
. Since the association adds a method with that name to its model, using an association with the same name as one provided by ActiveEntity::Base
will override the method inherited through ActiveEntity::Base
and will break things. For instance, attributes
and connection
would be bad choices for association names, because those names already exist in the list of ActiveEntity::Base
instance methods.