Associations
Associations are the relationships, links, you create between Models. Associations are like fields in that they add properties to whatever Content is created from their Model; however, whereas fields add data, Associations add relationships, or references, to other content objects within the system.
Whatever you name the Association, when you have a Content object in a Template or are referring to one from the API, Associated objects will be available through that name. When creating Associations, there is the Source Model and the Target Model. There are a number of types of Associations, based on how the Source Model and the Target Model can be related to each other:
- Has One — The Source Model may be associated to only one Target Model type. Example: Article (Source Model) has_one Category (Target Model).
- Has Many — The Source Model may have as many of the Target Model content objects as desired, though the Target objects may belong to only one Source object. Example: Blog (Source Model) has_many Blog Posts (Target Model).
- Belongs To — This is a reciprocal relationship created for both Has One and Has Many. When either of those Association types is selected, a corresponding Belongs To is automatically created in response. An object can belong to only one other object. Example: Blog Post (Source Model) has_many Blog Comments (Target Model), which means Blog Comment automatically belongs_to Blog Post. OR Blog Comment (Source Model) belongs_to Blog Post (Target Model), which means Blog Post automatically has_many Blog Comments.
- Has and Belongs To Many — This Association type has no restrictions on how many content objects can be related either way. Has and Belongs to Many is its own reciprocal. Example: Project has_and_belongs_to_many Developers. A project has many developers and developers can work on many projects.
Since an Association must always be bidirectional, the reciprocal type of Association is automatically created when the Model is saved. Has One and Has Many are reciprocal with Belongs To, and Has and Belongs to Many is reciprocal with itself. If you don’t specify a name for each Association you create, a name is generated automatically from the name of the associated Model. Feel free to change these default Association names to something more fitting to your concept of what the Association is.
Associations can also be set to “displayed,” like fields. In this case, the main display field of the associated content is used as the value shown.