module ActiveEntity::Associations::ClassMethods
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.
Public Instance Methods
# File lib/active_entity/associations.rb, line 149 def association_names @association_names ||= if !abstract_class? reflections.keys.map(&:to_sym) else [] end end
# File lib/active_entity/associations.rb, line 134 def embedded_in(name, **options) reflection = Embeds::Builder::EmbeddedIn.build(self, name, options) Reflection.add_reflection self, name, reflection end
# File lib/active_entity/associations.rb, line 158 def embeds_association_names @association_names ||= if !abstract_class? reflections.select { |_, r| r.embedded? }.keys.map(&:to_sym) else [] end end
# File lib/active_entity/associations.rb, line 144 def embeds_many(name, **options) reflection = Embeds::Builder::EmbedsMany.build(self, name, options) Reflection.add_reflection self, name, reflection end
# File lib/active_entity/associations.rb, line 139 def embeds_one(name, **options) reflection = Embeds::Builder::EmbedsOne.build(self, name, options) Reflection.add_reflection self, name, reflection end