When we add the belongs_to
line to a model in Ruby on Rails, it introduces several helpful methods to manage associations. Some of them are pretty familiar to most of us, but others aren’t, so here’s a brief explanation.
To present each method, we are going to base on this example:
class Post < ApplicationRecord
belongs_to :author
end
1 & 2 — Setter / Getter
Nobody should be surprised by these two. You can set the associated object or retrieve it.
# This sets the author association for the post.
post.author = new_author
# This fetches the author associated with the post.
post.author
3 — Build
A new author instance can be built, which means that the object is initialized but it’s not saved.
# Initializes a new Author object for the post without saving it to the database
post.build_author(name: "John Doe")
4 — Create
Another one pretty familiar: initializes and saves a new object for the association.
# Creates and saves a new Author object for the post.
post.create_author(name: "John Doe")
5 — Create or Raise
Similar to the one above, but raises an exception if the record that is being created is invalid.
# Creates and saves a new Author object, raising an error if the Author is invalid.
post.create_author!(name: "John Doe")
6 — Reload
Reloads the associated object from the database. Useful when you wanna make sure you have the most updated instance of that object in memory.
# Reloads the author associated with the post from the database.
post.author.reload
7 — Has Changed?
Checks if the association has changed in the current instance that hasn’t been saved yet. It’s useful to detect changes in the current state of the object before it is persisted in the database.
# Returns true if the author association has updates to be made.
post.author_changed?
8 — Has Previously Changed? (Before Last Save)
Checks if the associated object has changed in the last save.
# Returns true if there were updates sent in the last save
post.author_previously_changed?
So that’s it. Did you know all these helper methods that belongs_to
adds to our app? We would love to hear from you.