Belongs To
Last updated
Was this helpful?
Last updated
Was this helpful?
In this guide, we'll cover the BelongsTo
relationship using CQL's Active Record syntax. We'll start with an Entity-Relationship Diagram (ERD) to illustrate how this relationship works and continuously build upon this diagram as we introduce new relationships in subsequent guides.
BelongsTo
Relationship?The BelongsTo
association in a database indicates that one entity (a record) refers to another entity by holding a foreign key to that record. For example, a Comment
belongs to a Post
, and each comment references the Post
it is associated with by storing the post_id
as a foreign key.
Let's say you have a blog system where:
A Post can have many Comments.
A Comment belongs to one Post.
We'll start by implementing the BelongsTo
relationship from the Comment
to the Post
.
We'll first define the posts
and comments
tables using CQL's schema DSL.
posts table: Contains the blog post data (title, body, and published date).
comments table: Contains the comment data and a foreign key post_id
which references the posts
table.
Next, we'll define the Post
and Comment
structs in CQL.
In the Comment
model, we specify the belongs_to :post, Post, foreign_key: :post_id
association. This links each comment to its parent post. The Comment
model must have a post_id
attribute (matching the foreign_key
option) that stores the id
of the associated Post
.
Now that we have defined the Post
and Comment
models with a belongs_to
relationship, let's see how to create and query records in CQL.
Option 1: Create Parent, then Child
Option 2: Create Child and Associated Parent Simultaneously (if needed)
If you have a Comment
instance and want to create its Post
at the same time (less common for belongs_to
primary creation flow but possible via association methods):
Note: create_association
(like create_post
) will create and save the associated object (Post
) and set the foreign key on the current object (new_comment
). The current object itself (new_comment
) still needs to be saved if it's new.
Option 3: Build Associated Parent (without saving parent yet)
Once we have a comment, we can retrieve the associated post using the belongs_to
association.
In this example, comment.post
will fetch the Post
associated with that Comment
.
In this guide, we've covered the basics of the belongs_to
relationship in CQL. We:
Defined the Post
and Comment
tables in the schema.
Created the corresponding models, specifying the belongs_to
relationship in the Comment
model.
Showed how to create and query records using the belongs_to
association.
In the next guides, we'll build on this ERD and introduce other types of relationships like has_one
, has_many
, and many_to_many
. Stay tuned for the next part where we'll cover the has_many
relationship!
Feel free to play around with this setup and extend the models or experiment with more queries to familiarize yourself with CQL's Active Record capabilities.